java 中List排序函数Collections.sort的用法详解

List排序函数Collections.sort

1.Java提供的默认排序算法

List list = new ArrayList();
list.add(53.6);
list.add(45.9);
list.add(75.1);
list.add(89.3);
list.add(20.8);

//升序
Collections.sort(list);
System.out.println(list.toString());
输出结果:[20.8, 45.9, 53.6, 75.1, 89.3]


List list = new ArrayList();
list.add("张三");
list.add("李四");
list.add("王二");
list.add("李明");
list.add("杨洋");

//升序
Collections.sort(list,Collator.getInstance(java.util.Locale.CHINA));//注意:是根据的汉字的拼音的字母排序的,而不是根据汉字一般的排序方法
System.out.println(list.toString());
输出结果:[李明, 李四, 王二, 杨洋, 张三]

2.重载排序算法

        //根据map里某个key的value值进行升序排序
        ListString, Object>> companys = new ArrayList<>();
        LinkedTreeMap<String, Object> map1 = new LinkedTreeMap<>();
        map1.put("name", "中国");
        map1.put("percent", "12%");
        map1.put("span", 2.34);
        companys.add(map1);

        LinkedTreeMap<String, Object> map2 = new LinkedTreeMap<>();
        map2.put("name", "四川");
        map2.put("percent", "11%");
        map2.put("span", 1.34);
        companys.add(map2);

        LinkedTreeMap<String, Object> map3 = new LinkedTreeMap<>();
        map3.put("name", "云南");
        map3.put("percent", "10%");
        map3.put("span", 2.08);
        companys.add(map3);

        //重载排序算法
        Collections.sort(companys, new ComparatorString, Object>>() {
            @Override
            public int compare(LinkedTreeMap<String, Object> arg0,LinkedTreeMap<String, Object> arg1) {
                Double span1 = (Double) arg0.get("span");
                Double span2 = (Double) arg1.get("span");
                return span1.compareTo(span2);
            }
        }); 
        System.out.println(companys.toString());

输出结果:[{name=四川, percent=11%, span=1.34}, {name=云南, percent=10%, span=2.08}, {name=中国, percent=12%, span=2.34}]

你可能感兴趣的:(java)