Java8 stream 可简洁实现对象List根据对象的某一字段进行去重。
实现代码如下:
根据去重场景修改代码中的对象及去重字段即可。
//根据Student对象的age进行去重
studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student :: getAge))), ArrayList::new));
注:若存在两个 age 相同的student,其他数据不同,留下的数据是靠前的数据,去除的是靠后的数据。
例如:
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("1","哈哈","18"));
studentList.add(new Student("2","哼哼","18"));
studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student :: getAge))), ArrayList::new));
根据 age 去重后结果:学生“哈哈”被保留,学生“哼哼”被去除。
查看更多常用流式操作 Java8 stream 常用操作汇总