如何实现java8 list按照元素的某个字段去重
程序员文章站
2022-04-25 20:19:30
list 按照元素的某个字段去重
@data
@allargsconstructor
@noargsconstructor
public class s...
list 按照元素的某个字段去重
@data @allargsconstructor @noargsconstructor public class student { private integer age; private string name; }
测试数据
list<student> studentlist = lists.newarraylist(); studentlist.add(new student(28, "river")); studentlist.add(new student(12, "lucy")); studentlist.add(new student(33, "frank")); studentlist.add(new student(33, "lucy"));
java8 通过tree set 去重
list<student> studentdistinctlist = studentlist.stream() .collect(collectors.collectingandthen (collectors.tocollection(() -> new treeset<>(comparator.comparing(t -> t.getname()))), arraylist::new ) ); system.out.println(new gson().tojson(studentdistinctlist));
扩展distinct 方法去重
list<student> studentdistinct2list = studentlist.stream().filter(streamutil.distinctbykey(t->t.getname())) .collect(collectors.tolist()); system.out.println(new gson().tojson(studentdistinct2list));
工具类
public class streamutil { /** * https://*.com/questions/23699371/java-8-distinct-by-property * @param keyextractor * @param <t> * @return */ public static <t> predicate<t> distinctbykey(function<? super t, ?> keyextractor) { set<object> seen = concurrenthashmap.newkeyset(); return t -> seen.add(keyextractor.apply(t)); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 暗恋一美女同事许久
下一篇: 一句话,不同解释,同样好笑