如何實(shí)現(xiàn)java8list按照元素的某個(gè)字段去重

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

創(chuàng)新互聯(lián)公司是一家專業(yè)提供北塔企業(yè)網(wǎng)站建設(shè),專注與做網(wǎng)站、成都網(wǎng)站制作、H5頁(yè)面制作、小程序制作等業(yè)務(wù)。10年已為北塔眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。

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

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

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 通過(guò)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));

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

網(wǎng)頁(yè)名稱:如何實(shí)現(xiàn)java8list按照元素的某個(gè)字段去重
文章位置:http://muchs.cn/article16/ihghgg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、移動(dòng)網(wǎng)站建設(shè)、企業(yè)建站、網(wǎng)站收錄、標(biāo)簽優(yōu)化響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁(yè)設(shè)計(jì)公司