如有一个Person列表,项目中需要根据Person类里面的name属性去重。
List<Person> persons = new ArrayList();
//赋值初始化过程省略
List<Person> uniqueByName = persons.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);
业务场景简单描述:先从数据库取出字段C的值为c的数据列表,再根据字段A=x过滤列表,然后依次根据字段A和字段B进行排序(字段A相同的话,根据字段B排序),最后去重。
代码简单实例:
List<Person> list = objectService.list(new QueryWrapper<Person>().eq("C","c"));
List<Person> after_list=list.stream().filter(Person->Person.getA() == x).collect(Collects.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getA).thrnComparing(Person::getB))),ArrayList::new));
文章展示了如何在Java中使用StreamAPI和Comparator对Person列表进行去重操作,首先根据name属性去重,然后从数据库中查询字段C为c的数据,进一步过滤出字段A等于x的Person对象,接着按照字段A和字段B进行排序,最后通过TreeSet实现排序和去重,结果转换回ArrayList。
348

被折叠的 条评论
为什么被折叠?



