stream根据某个字段去重(对象的某个字段去重)
方案一
重写
实体equals、hashcode方法 [重要]- 使用
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()))
)
);