如果不能重写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的distinct,根据对象的positionId去重后转list输出。注意:不能重写equals方法

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

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