Java List按照某字段去重的使用示例
嘚吧嘚
Java8流的新類java.util.stream.Collectors實現(xiàn)了java.util.stream.Collector接口,同時又提供了大量的方法對流(stream)的元素執(zhí)行各種統(tǒng)計操作。
distinct
示例一
List<Map<String, Object>> mapList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
HashMap<String, Object> e = new HashMap<>();
e.put("name", "Mike");
e.put("age", 19);
mapList.add(e);
HashMap<String, Object> f = new HashMap<>();
f.put("name", "John");
f.put("age", 19);
mapList.add(f);
}
System.out.println(mapList);
System.out.println("===================去重===================");
List<Map<String, Object>> collect = mapList.stream().distinct().collect(Collectors.toList());
collect.forEach(System.out::println);
執(zhí)行結果如下

但是這種方式必須要每個鍵值對都一樣,才會被判定成重復的,否則不會被判為重復,如下。
示例二
List<Map<String, Object>> mapList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
HashMap<String, Object> e = new HashMap<>();
e.put("name", "Mike");
e.put("age", 19 + i);
mapList.add(e);
HashMap<String, Object> f = new HashMap<>();
f.put("name", "John");
f.put("age", 19 + i);
mapList.add(f);
}
System.out.println(mapList);
System.out.println("===================去重===================");
List<Map<String, Object>> collect = mapList.stream().distinct().collect(Collectors.toList());
collect.forEach(System.out::println);
執(zhí)行結果如下

雖然name的值一樣,但是age的值不一樣,所以沒有被被判定為重復。
所以如果要按照某字段去重,請采用如下方式。
根據(jù)某個字段去重
List<Map<String, Object>> mapList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
HashMap<String, Object> e = new HashMap<>();
e.put("name", "Mike");
e.put("age", 19 + i);
mapList.add(e);
HashMap<String, Object> f = new HashMap<>();
f.put("name", "John");
f.put("age", 19 + i);
mapList.add(f);
}
System.out.println(mapList);
System.out.println("===================去重===================");
List<Map<String, Object>> collect = mapList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> String.valueOf(p.get("name"))))), ArrayList::new));
collect.forEach(System.out::println);
執(zhí)行結果如下

代碼中用到了“Collectors.collectingAndThen”,這個函數(shù)是干什么的呢?咱們繼續(xù)。
Collectors.collectingAndThen()
從函數(shù)名字就可以看出,這個函數(shù)分為兩個部分,一個是collecting,另一個是then。
Collectors.collectingAndThen()函數(shù)很像map and reduce,它可接受兩個參數(shù),第一個參數(shù)用于reduce(collecting)操作,而第二參數(shù)用于map(then)操作。
也就是,先把流中的所有元素傳遞給第一個參數(shù),然后把生成的集合傳遞給第二個參數(shù)來處理。
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Double result = list.stream().collect(Collectors.collectingAndThen(Collectors.averagingLong(item -> item * 2), res -> res * 3));
System.out.println("result = " + result);
執(zhí)行結果如下

邏輯如下
把[1,2,3,4]這個集合傳遞給item -> item * 2這個lambda表達式,計算得出結果為[2,4,6,8]
然后再把[2,4,6,8]傳遞給Collectors.averagingLong表達式,計算得出5.0
然后傳遞給res -> res * 3這個lambda表達式,計算得到結果為15.0
到此這篇關于Java List按照某字段去重的使用示例的文章就介紹到這了,更多相關Java List字段去重內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

