使用Java8的stream对list中的对象进行去重
文章目录
首先我们有一个对象属性如下
@Data
public class Person {
private String id;
private String name;
private String sex;
}
我们根据属性name来去重,去重代码如下
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)
);
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论