首页 > 解决方案 > 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

任何建议,如何实现这一目标?

标签: javacollectionsjava-8group-bycollectors

解决方案


未经测试,但看起来,您正在寻找类似的东西:

    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())));

推荐阅读