1. list去重
List<String> list = new ArrayList<>();
list.add("123");
list.add("22");
list.add("22");
list.add("123");
list.add("234");
list.add("234");
list.add("99");
list.add("99");
list = list.stream().distinct().collect(Collectors.toList());
System.out.println(list.toString());
2. 根据对象中的某个字段进行list去重
List<User> list = new ArrayList<User>();
list.add(new User("小南", 23, "18335888888"));
list.add(new User("小南", 22, "18335888888"));
list.add(new User("小南", 21, "18335888888"));
list.add(new User("小南", 20, "18335888888"));
list = list.stream().filter(distinctByKey(User :: getName)).collect(Collectors.toList());
System.out.println(list.toString());
private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
3. 排序
list = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
list = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
list = list.stream().sorted(Comparator.comparing(User::getAge,Comparator.nullsLast(Integer::compare).reversed())).collect(Collectors.toList());
list = list.stream().sorted(Comparator.comparing(User::getAge,Comparator.nullsFirst(Integer::compare).reversed())).collect(Collectors.toList());
4. 排序并去重
list = list.stream().sorted(Comparator.comparing(User::getAge,Comparator.nullsLast(Integer::compare).reversed())).filter(distinctByKey(User :: getName)).collect(Collectors.toList());
|