Stream流中,根据对象去重+指定对象中的属性去重

首先定义一个学生类:

@Data
@AllArgsConstructor
public class Student {
    
    

    private Long id;
    private String name;
    private Integer age;
    private Double high;
}

在main方法中构造四个对象,其中第四个对象为重复对象,现在进行对象的去重、以及对象中某一属性的去重操作

public class ListStreamDistinctTest {
    
    

    public static void main(String[] args) {
    
    
        // 一个集合中放入4个学生对象
        List<Student> list = new ArrayList<>();
        list.add(new Student(10002L, "ZhangSan", 18, 175.2));
        list.add(new Student(10001L, "LiSi", 19, 175.2));
        list.add(new Student(10004L, "Peter", 19, 170.8));
        list.add(new Student(10004L, "Peter", 19, 170.8));
	}
	  }

一、根据对象去重:
以下代码写于main函数中:

 System.out.println("整个对象去重:");
        list.stream().distinct()
        .forEach(System.out::println);

运行结果如下,可以看到,stream流的distinct只是将对象去重,将相同的第三个和第四个对象去重了
在这里插入图片描述
二、根据对象中某一属性(年龄)去重:
方法一、自定义其他方法:
以下代码写于main函数中:

 System.out.println("指定age属性去重(方法一):");
        list.stream().filter(distinctByKey1(s -> s.getAge()))
          .forEach(System.out::println);

此处定义一个静态方法:distinctByKey1,写于main函数以外:

  static <T> Predicate<T> distinctByKey1(Function<? super T, ?> keyExtractor) {
    
    
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

运行结果:
在这里插入图片描述

方法二:
以下代码写于main函数中:

 System.out.println("指定age属性去重(方法二):");
        TreeSet<Student> students = new TreeSet<>(Comparator.comparing(s -> s.getAge()));
        for (Student student : list) {
    
    
            students.add(student);
        }
        new ArrayList<>(students)
                .forEach(System.out::println);

通过构造treeset,遍历list,将元素添加到treeset中完成去重,再转换成List,运行结果:
在这里插入图片描述

方法三:
以下代码写于main函数中:

 System.out.println("指定age属性去重(方法三):");
        list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getAge()))), ArrayList::new))
                .forEach(System.out::println);

作为方法二的变形,运行结果:
在这里插入图片描述

参考链接:
Java8 stream-List去重distinct、和指定字段去重

扫描二维码关注公众号,回复: 16258712 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_42260782/article/details/129826507