多个集合交集
最近在工作中需要些一个接口,就是求多个教室的公共课程,这就涉及到求多个集合的交集。
假设集合中元素的类型为Object,那多个集合数据结构为List<List>。我们知道,求两个集合的交集方法为list1.retainAll(list2)。对多个集合求交集也就是多个集合两两求交集,这就可以使用Java8新语法中的reduce方法。
List<List<Object>> allCourses = ...;//得到所有课程,每个教室的课程对应一个List集合
//规约操作,两两求交集
List<Object> commonCourses = allCourses.stream()
.reduce((list1, list2) -> {
list1.retainAll(list2);
return list1;
})
.orElse(Collections.emptyList());
java8 筛选出List不被另一个List包含的元素
List<String> delTagGroup = new ArrayList<>();//需要删除的
List<String> originGroupId = qwTagGroupEntityList.stream().map(QwTagGroupEntity::getGroupId).collect(Collectors.toList());//原有的
List<String> newGroupId = corpTagList.getTag_group().stream().map(CorpTagList.TagGroupBean::getGroup_id).collect(Collectors.toList());//新的
delTagGroup = originGroupId.stream().filter(o->!newGroupId.contains(o)).collect(Collectors.toList());//新的不在原有里面的
list中筛选出另一个list中没有的对象
// 从list2中筛选出list1中没有的元素
List<SysUser> diff = list2.stream().filter(
user2 -> !list1.stream().map(user1 -> user1.getUserName()).collect(Collectors.joining()).contains(user2.getUserName()))
.collect(Collectors.toList());
list1.addAll(diff);