如果需要对一个list进行去重,最简单的写法是
List<DocumentSearch> objects = new ArrayList<>(); objects.addAll(documentSearchList); // objects.addAll(documentSearchTagsList); return objects.stream().distinct().collect(Collectors.toList());
重点就是distinct方法,需要成员实现hashCode和equals方法
还有一种更变态的写法
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())
3 如果是要根据某个属性,进行去重,该属性未必是equals方法中的比较字段
studentList = studentList.stream().collect( collectingAndThen( toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new) ); out.print("根据名字去重后 :"); out.println(objectMapper.writeValueAsString(studentList)); }