新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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

list 按照元素的某个字段去重

创新互联公司是一家专业提供北塔企业网站建设,专注与做网站、成都网站制作、H5页面制作、小程序制作等业务。10年已为北塔众多企业、政府机构等服务。创新互联专业网络公司优惠进行中。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer age;
private String name;
}

测试数据

List 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 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 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 
* @return
*/
public static  Predicate distinctByKey(Function<? super T, ?> keyExtractor) {
Set seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}

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


新闻标题:如何实现java8list按照元素的某个字段去重
标题来源:http://www.wjwzjz.com/article/ihghgg.html