首先咱們有一個對象屬性以下java
@Data public class Person { private String id; private String name; private String sex; }
咱們根據屬性name來去重,去重代碼以下code
List<Person> persons = new ArrayList(); //賦值初始化過程省略 List<Person> uniqueByName = persons.stream().collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new) );
根據name,sex兩個屬性去重對象
List<Person> persons = new ArrayList(); //賦值初始化過程省略 List<Person> uniqueByNameAndSex = persons.stream().collect( Collectors. collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new) );