首先咱们有一个对象属性以下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) );