欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何实现java8 list按照元素的某个字段去重

程序员文章站 2024-01-15 21:14:10
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));
}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。