java stream list 删除list中对象属性重复元素

有时我们需要删除list中重复的对象,可以通过stream filter及相关操作,将其删除

    public static void main(String[] args) {
    //数据模拟
        List<Keywords> list = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Keywords keywords = new Keywords();
            keywords.setKeyword("a");
            list.add(keywords);
        }
        Keywords keywords = new Keywords();
        keywords.setKeyword("1");
        list.add(keywords);
  
//通过stream list的filter操作,过滤掉list中的重复值
        List<Keywords> collect = list.stream().filter(distinctByKey(Keywords::getKeyword)).collect(Collectors.toList());
        System.out.println(collect);
    }

/**
  * 获取list中对象属性的重复值
*/
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容