Java Web知识Java学习笔记

对集合中的元素进行排序的简单方法

2016-11-13  本文已影响36人  GuaKin_Huang

/**比较中文并排序
 * Created by hp on 2016/11/7.
 */

public class CollatorComparator implements Comparator<String> {

    Collator collator = Collator.getInstance();
    @Override
    public int compare(String o1, String o2) {
        CollationKey key1 = collator.getCollationKey(o1);
        CollationKey key2 = collator.getCollationKey(o2);
        return key1.compareTo(key2);
    }
}

例子:

public class Main {
    public static void main(String[] args){
        Student student1 = new Student("张三", 15, "男");
        Student student2 = new Student("李三", 45, "男");
        Student student3 = new Student("王三", 55, "男");
        Student student4 = new Student("黄三", 15, "男");
        Student student5 = new Student("陈列", 75, "男");
        Student student6 = new Student("电话费", 95, "男");

        //对于list而言
        
        ArrayList<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
        list.add(student6);

        //排序前
        for (Student s :
                list) {
            System.out.println(s);
        }
        System.out.println();

        //可以通过内部类方式实现
        Collections.sort(list, new Comparator<Student>() {
            Collator collator = Collator.getInstance();
            @Override
            public int compare(Student o1, Student o2) {
                CollationKey collationKey1 = collator.getCollationKey(o1.getName());
                CollationKey collationKey2 = collator.getCollationKey(o2.getName());
                return collationKey1.compareTo(collationKey2);
            }
        });

        //排序后
        for (Student s :
                list) {
            System.out.println(s);
        }

        System.out.println();


        //对于map而言
        // 可以另外实现一个类Comparator
        TreeMap<String, Student> treeMap = new TreeMap<>(new CollatorComparator());

        treeMap.put("张三", student1);
        treeMap.put("李三", student2);
        treeMap.put("王三", student3);
        treeMap.put("黄三", student4);
        treeMap.put("陈列", student5);
        treeMap.put("电话", student6);


        Set<String> strings = treeMap.keySet();

        for (String str :
                strings) {
            System.out.println(str);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读