下面归纳出几种常见的去重方法:
使用stream流collectingAndThen()
//根据某一属性去重
studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
// 利用 TreeSet 的排序去重构造函数来达到去重元素的目的
() -> new TreeSet<>(Comparator.comparing(Student::getId))), ArrayList::new));
通过filter方法去重
我们首先创建一个方法作为 Stream.filter() 的参数,其返回类型为 Predicate,原理就是判断一个元素能否加入到 Set 中去,代码如下:
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
studentList = studentList.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList());
distinct去重一般都是用于去重List<String>这样的列表集合,他要求两个元素的所有属性全部一样
studentList = studentList.stream().distinct().collect(Collectors.toList());
linkHashSet去重
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
ArrayList<String> list = new ArrayList<>();
linkedHashSet.addAll(list);
list.clear();
list.addAll(linkedHashSet);
set去重
利用Map的key属性 不可重复
ArrayList<String> list = new ArrayList<>();
Set set = new HashSet();
list.stream().forEach(s -> {
set.add(s);
});
嵌套循环去重
Arrays.sort(list.toArray());
for (int i =0;i<list.size()-1;i++){
for (int j=list.size()-1;j>i;j--){
if(list.get(j).equals(list.get(i))){
list.remove(j);
}
}
}