大明新时代,吹神幻影,神之浩劫微信问卷答题
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://stackoverflow.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)); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论