在业务逻辑越来越复杂的当前,去重是业务逻辑也很多,下面介绍几种
List(字符串)去重
List<String> collect = list.stream().distinct().collect(Collectors.toList());
List(对象),去重其属性一,单一属性,下面还有去多属性
推荐:速度比接下来的快
List<对象> quchong = data.stream().filter(distinctByKey(对象 -> 对象.get属性())).distinct()
.collect(Collectors.toList());
static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
List(对象),去重其属性二
List<对象> unique = data.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(对象::get属性))),
ArrayList::new));
List(对象),去重其属性二(多属性)
List<对象> uniques = data.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<对象>(
Comparator.comparing(对象-> 对象.get属性() + ";" + 对象.get属性()))),
ArrayList::new));