List、Set排序操作

298 阅读1分钟

简单排序

//升序 
Arrays.asList(1, 2, 3, 4).stream().sorted().collect(Collectors.toList()); 
//降序: reversed 
Arrays.asList(1, 2, 3, 4).stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

对一个对象类型的集合排序: Comparator

//升序 
objList.stream().sorted(Comparator.comparing(Context::getKey)).collect(Collectors.toList()); 

//降序: reversed 
objList.stream().sorted(Comparator.comparing(Context::getKey).reversed()).collect(Collectors.toList()); 

//多条件排序: thenComparing 
objList.stream().sorted(Comparator.comparing(Context::getKey).thenComparing(Context::getValue))).collect(Collectors.toList());