我有一个返回 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;
返回类(class)级别的 map -> 度数集。
例如,它读取所有类(class)并返回如下 map :
{"undergraduate" : ["BTech", "BSc", "BE"],
"masters": ["MTech", "MBA"],
"Executive": ["PGDBM", "EECP"]}
这是我的类(class):
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()))
);
这不起作用,我收到以下编译时错误:
no instance(s) of type variable(s) exist so that List conforms to String inference variable T has incompatible bounds: equality constraints: String lower bounds: 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())));
关于Java 8 分组并附加到集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647974/