java - Java 8 分组并附加到集合
问题描述
我有一个函数,它返回Map<String, Set<String>>
java 8 之前的代码:
Map<String, Set<String>> degreeMap = new HashMap<>();
for(Course course : courses){
Set<String> cList = degreeMap.get(course.getCourseLevel().toString());
if(Objects.nonNull(cList)){
cList.addAll(course.getMasterDegree()); //this is what i want to append to the old set
degreeMap.put(course.getCourseLevel().toString(), cList);
} else{
degreeMap.put(course.getCourseLevel().toString(), new HashSet<>(course.getMasterDegree()));
}
}
return degreeMap;
它返回课程级别的地图 -> 度数集。
例如,它读取所有课程并返回如下地图:
{"undergraduate" : ["BTech", "BSc", "BE"],
"masters": ["MTech", "MBA"],
"Executive": ["PGDBM", "EECP"]}
这是我的课程:
public class Course {
private List<String> masterDegree;
private CourseLevel courseLevel;
}
但我想用 Java 8 风格编写这段代码。为此,我尝试了这个:
Map<String, Set<String>> degreeMap = courses.stream().collect(
Collectors.groupingBy(c -> c.getCourseLevel().toString(),
Collectors.mapping(c -> c.getMasterDegree(), Collectors.toSet()))
);
这不起作用,我收到以下编译时错误:
不存在类型变量的实例,因此 List 符合 String 推断变量 T 具有不兼容的边界:等式约束:String 下限:List
任何建议,如何实现这一目标?
解决方案
未经测试,但看起来,您正在寻找类似的东西:
return courses.stream()
.collect(Collectors.toMap(course -> course.getCourseLevel().toString(),
course -> new HashSet<>(course.getMasterDegree()),
(set1, set2) -> Stream.of(set1, set2)
.flatMap(Set::stream).collect(Collectors.toSet())));
推荐阅读
- linux - 如何打印文件慢?
- android - 如何正确共享文件 android 11
- c# - Add-Migration 自动设置 'onDelete: ReferentialAction.Restrict);'
- ios - 如何创建自定义段顶部选项卡视图控制器?(迅速)
- amazon-web-services - AWS ECS:增加容器根卷大小,而不是数据卷大小
- php - 带有单例子类化的 PHP 7.3.x 中的已知错误?
- spring - Spring WebClient 编码 + 字符不正确
- python - 如何将matplotlib图表保存到python中的临时文件?
- c# - 如何在 Windows 窗体上动态向下滚动页面?
- python - 如何调试此代码,该代码旨在计算以下系列到第 n 项(参数)的总和