stream根据某个字段去重(对象的某个字段去重)

stream根据某个字段去重(对象的某个字段去重)

方案一

  1. 重写实体equals、hashcode方法 [重要]
  2. 使用infoList.stream().distinct().collect(Collectors.toList());得到结果

方案二

返回结果为List

根据productId字段过滤
infoList为源List集合

 ArrayList<Product> collect1 = infoList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(a -> a.getProductId()))),
                            ArrayList::new
                    )
            );

返回结果为Set

  TreeSet<Product> collect = infoList.stream().collect(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(a -> a.getProductId()))
                    )
            );

おすすめ

転載: blog.csdn.net/qq_41070393/article/details/126282175