List unique = list.stream().distinct().collect(Collectors.toList());
List<String>通过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://blog.xqlee.com/article/618.html