Java中使用lamda表示式實現根據物件屬性去重
阿新 • • 發佈:2018-12-26
本文演示根據物件屬性對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()); } } }
輸出結果: