如果不能重写 equals 方法,可以通过在 distinct 方法中自定义一个比较器来判断两个对象是否相等。具体实现如下:

List<Object> distinctList = list.stream()
        .filter(Objects::nonNull)
        .filter(DistinctByKey.distinctByKey(o -> o.getPositionId()))
        .collect(Collectors.toList());

其中,DistinctByKey 是一个自定义的比较器类,实现如下:

class DistinctByKey {
    public 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;
    }
}

这里使用了 ConcurrentHashMap 来存储已经出现过的 key,如果该 key 已经存在,则过滤掉该对象,否则将该 key 加入到 map 中,并保留该对象。这样就可以实现根据对象的 positionId 去重后转 list 输出。

Java Stream 去重:基于 positionId 属性的 distinct 操作

原文地址: https://www.cveoy.top/t/topic/lLb7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录