Java中使用lamda表达式实现根据对象属性去重
本文演示根据对象属性对List中的对象去重
新建实体类
public class Person {
private String id;
private String name;
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
根据Person对象的id属性去重以及查看结果:
public class MainTest {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
Person p1 = new Person("1", "123");
Person p2 = new Person("2", "123");
Person p3 = new Person("1", "456");
list.add(p1);
list.add(p2);
list.add(p3);
List<Person> result = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<Person> (Comparator.comparing(p -> p.getId()))),
ArrayList::new));
for (Person person : result) {
System.out.println(person.getId() + " " + person.getName());
}
}
}
输出结果: