使用 Stream 的 distinct() 方法
這個(gè)方法會(huì)根據(jù)元素的 hashCode() 和 equals() 方法來判斷是否重復(fù)。如果是自定義的類,需要重寫這兩個(gè)方法。
示例:文章來源地址http://www.zghlxwxcb.cn/news/detail-541901.html
//利用java8的stream去重
List uniqueList = list.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueList.toString());
使用 collectingAndThen() 和 toCollection() 方法
這個(gè)方法可以根據(jù)元素的某個(gè)屬性或者多個(gè)屬性來去重,比如 name 或者 name+address。這個(gè)方法會(huì)使用 TreeSet 來排序元素,所以不能保持原來的順序。
示例:
//根據(jù)name屬性去重
List<User> lt = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(Comparator.comparing(User::getName))),
ArrayList::new)
);
System.out.println("去重后的:" + lt);
使用 filter() 方法
這個(gè)方法需要自定義一個(gè) Predicate 函數(shù),用一個(gè) Set 來記錄已經(jīng)出現(xiàn)過的元素,然后過濾掉重復(fù)的元素。文章來源:http://www.zghlxwxcb.cn/news/detail-541901.html
示例:
//定義一個(gè)Predicate函數(shù)
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
//根據(jù)age屬性去重
list.stream().filter(distinctByKey(s -> s.getAge()))
.forEach(System.out::println);
到了這里,關(guān)于java stream去重的幾種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!