Java教程

JAVA8 Stream List中元素根据元素属性进行去重

本文主要是介绍JAVA8 Stream List中元素根据元素属性进行去重,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
// 创建一个包含DeptEntity对象的List,并向其中添加若干元素
List<DeptEntity> deptEntityList= new ArrayList<>();
deptEntityList.add(new DeptEntity(1, '部门1'));
deptEntityList.add(new DeptEntity(1, '部门1'));
deptEntityList.add(new DeptEntity(2, '部门2'));

// 使用java8的stream流进行元素去重(根据DeptEntity中的id进行元素去重)
ArrayList<DeptEntity> disList = deptEntityList.stream().collect(
        Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(DeptEntity::getId))), ArrayList::new))
这篇关于JAVA8 Stream List中元素根据元素属性进行去重的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!