LIST 实体类根据多个字段去重
现在有一个实体类Person,属性有三个,分别是name,age,address,根据这三个属性将list<Person>中三个字段都相同的数据进行去重。
//创建list,添加数据
List<Person> list = new ArrayList<>();
list.add(new Person("Tom", 15, "America"));
list.add(new Person("Tam", 16, "China"));
list.add(new Person("Tom", 15, "Japan"));
list.add(new Person("Tcm", 18, "Russia"));
list.add(new Person("Tom", 15, "America"));
list.add(new Person("Tdm", 16, "America"));
list.add(new Person("Tem", 17, "America"));
// 根据三个字段去重
List<Person> lst = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + "#" + o.getAge() + "#" + o.getAddress()))),
ArrayList::new));
// 遍历输出一下
lst.forEach(person -> System.out.println(person.toString()));
//结果:
Person [name=Tam, age=16, address=China]
Person [name=Tcm, age=18, address=Russia]
Person [name=Tdm, age=16, address=America]
Person [name=Tem, age=17, address=America]
Person [name=Tom, age=15, address=America]
Person [name=Tom, age=15, address=Japan]
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步