记录一下java去重的方法各种方法

1:正常使用的方法

forEach

2:java8  distinct 使用的方法

List collect = list.stream().distinct().collect(Collectors.toList());

不能复杂类型(对象不重写eqs)

3:java8  collectingAndThen 使用的方法 

ArrayList a1 = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(a -> (String)a.get("a")))), ArrayList::new));

 

4: 一个比较高大上的操作

List a2 = list.stream().filter(distinctByKey(a -> a.get("a"))).collect(Collectors.toList());
    
public static  Predicate distinctByKey(java.util.function.Function key) {
        //线程安全
        Map seen = new ConcurrentHashMap<>();
        //putIfAbsent 如果key不存在于map,插入并返回null,反之则返回对应key的value值
        return t -> seen.putIfAbsent(key.apply(t), Boolean.TRUE) == null;
    }

 

你可能感兴趣的:(java小知识)