java 8 stream List去重/集合去重
教程分享
>
Java教程
(8663)
2024-04-17 12:33:24
简介
本博文主要讲解在Java 8中 如何通过stream流的方式去重。
List<String>通过stream去重
List unique = list.stream().distinct().collect(Collectors.toList());
List<String>通过stream去重是非常简单的。就上面的一句代码搞定
List<对象>通过stream根据集合对象的某个属性或者某些属性去重
// Person 对象
public class Person {
private String id;
private String name;
private String sex;
<!--省略 get set-->
}
根据name去重
// 根据name去重
List<Person> unique = persons.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);
根据name sex两个属性去重
List<Person> unique = persons.stream().collect(
Collectors. collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
);
https://www.leftso.com/article/618.html