数字集合排序
对于集合内全部是数字的集合或者是数字字符串的集合排序,可以使用Collections的sort方法进行排序,如下:
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(4);
intList.add(54);
intList.add(5);
Collections.sort(intList);
intList.forEach(System.out::println);
List<String> strList = new ArrayList<>();
strList.add("1");
strList.add("4");
strList.add("54");
strList.add("5");
Collections.sort(strList);
intList.forEach(System.out::println);
}
输出如下:
对象数组排序
集合内存储的是对象的集合排序可以使用stream的sorted或者List自己的sort方法进行排序,实现如下:(需要注意的是对象集合排序,其实也是通过对象的某个属性进行排序,排序字段需要是可以排序的值,如下,可以使用数值型字符串排序,不能通过名称去排序。)
public static void main(String[] args) {
List<StudentVO> list = new ArrayList<>();
list.add(new StudentVO("1001","张三",24,"男","123"));
list.add(new StudentVO("1002","李四",23,"男","123"));
list.add(new StudentVO("1003","王五",24,"男","123"));
List<StudentVO> list1 = list.stream().sorted(Comparator.comparing(StudentVO::getStuNo).reversed()).collect(Collectors.toList());
list1.forEach(System.out::println);
list.sort(Comparator.comparing(StudentVO::getStuNo));
list.forEach(System.out::println);
}
输出如下:
List<Map<String, String>>集合排序
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("value", "12");
map.put("value", "34");
map.put("value", "54");
List<Map<String, String>> list1 = list.stream().sorted(Comparator.comparing((Map<String, String> t) -> (String.valueOf(t.get("value")))).reversed()).collect(Collectors.toList());
list集合去重
//根据对象的一个属性字段去重
list.stream().filter(distinctByKey(User::getUserId)).collect(Collectors.toList());
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
list集合利用stream group分组实现多个字段去重
//将多个字段组合成一个key值进行去重,然后返回一个新的去重后的集合
List<MeteorologicalStationPO> list = poList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(item -> item.getStationIdC() + ";" + item.getStationName()
+ ";" + item.getStationLevl() + ";" + item.getAdminCodeChn()
+ ";" + item.getLat() + ";" + item.getLon()))), ArrayList::new));