Java Stream 流集合去重排序

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());
//输出 [123, 22, 234, 99]

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. 排序

// 根据age排序 (正序)
list = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
//输出
//[User(name=小南, age=20, phone=18335888888), User(name=小南, age=21, phone=18335888888), User(name=小南, age=22, phone=18335888888), User(name=小南, age=23, phone=18335888888)]
// (倒序)
list = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
//输出
//[User(name=小南, age=23, phone=18335888888), User(name=小南, age=22, phone=18335888888), User(name=小南, age=21, phone=18335888888), User(name=小南, age=20, phone=18335888888)]
//如果排序字段为空将空的某一条默认排到开头还是结尾
//放到结尾
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());

猜你喜欢

转载自blog.csdn.net/weixin_43627706/article/details/123331939