日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時(shí)間:2023/12/2 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java list 字段去重_如何实现java8 list按照元素的某个字段去重 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

list 按照元素的某個(gè)字段去重

@Data

@AllArgsConstructor

@NoArgsConstructor

public class Student {

private Integer age;

private String name;

}

測試數(shù)據(jù)

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));

擴(kuò)展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));

}

}

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

總結(jié)

以上是生活随笔為你收集整理的java list 字段去重_如何实现java8 list按照元素的某个字段去重的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。