使用Collections.sorted(list)和Collections.sorted(list,Comparator)对基础数据类型集合或对象集合排序。
Collections.sorted(list)默认是升序排序的,如果需要倒序排序,需要自定义Comparator比较器。且看示例如下:
//默认排序都是从小到大的顺序排序 //对数字排序 List list = Arrays.asList(5, 2, 9, 3); System.out.println("源序列:"+list); Collections.sort(list); System.out.println("升序排列:"+list); //对字符串 List strList = Arrays.asList("adf", "jjdjf", "iure", "jad", "gdss"); System.out.println("源序列:"+strList); Collections.sort(strList); System.out.println("顺序排序:"+strList); //对字符串倒序排序,需要定义比较器 Collections.sort(strList, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }); System.out.println("倒序:"+strList); //对对象按某个字段倒序排序,需要定义比较器 Map<String, Double> map = new LinkedHashMap<>(); map.put("ab", 8.09); map.put("ann", 98.09); map.put("b", 55.09); map.put("cb", 7.09); map.put("ba", 98.09); //为了方便示例,这里将Map.Entry<String, Double>看成一个对象类,按value值顺序排列 List orderList = new ArrayList<Map.Entry<String, Double>>(map.entrySet()); System.out.println("插入顺序:"+orderList); Collections.sort(orderList, new Comparator<Map.Entry<String, Double>>() { @Override public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) { return o1.getValue().compareTo(o2.getValue()); } }); System.out.println("升序排列:"+orderList); }
以上示例结果如下:
源序列:[5, 2, 9, 3]
升序排列:[2, 3, 5, 9]
源序列:[adf, jjdjf, iure, jad, gdss]
顺序排序:[adf, gdss, iure, jad, jjdjf]
倒序:[jjdjf, jad, iure, gdss, adf]
插入顺序:[ab=8.09, ann=98.09, b=55.09, cb=7.09, ba=98.09]
升序排列:[cb=7.09, ab=8.09, b=55.09, ann=98.09, ba=98.09]
当然是用java8的lambda表达式进行排序更简单:
List<String> strList = Arrays.asList("adf", "jjdjf", "iure", "jad", "gdss"); System.out.println("源序列:" + strList); //对字符串使用java8新特性(lambda表达式)进行排序 strList = strList.stream().sorted((a, b) -> a.compareTo(b)).collect(Collectors.toList()); System.out.println("顺序排序:" + strList); //对字符串倒序排序,不需要定义比较器 strList = strList.stream().sorted((a, b) -> b.compareTo(a)).collect(Collectors.toList()); System.out.println("倒序:" + strList);
结果如下:
源序列:[adf, jjdjf, iure, jad, gdss]
顺序排序:[adf, gdss, iure, jad, jjdjf]
倒序:[jjdjf, jad, iure, gdss, adf]
顺便提一下:
HashMap是随机无序的,LinkedHashMap是维持插入顺序,TreeMap是默认按key升序排列