Java 8 分组并附加到集合

标签 java collections java-8 group-by collectors

我有一个返回 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/

相关文章:

c# - 使用 LINQ 将 'ArrayList' 转换为 'List<string>'(或 'List<T>')

Java 8 Instant.range 和 Instant.with 出现不一致

java - ubuntu更新后tomcat 8停止工作

java - 通常在哪里应用 JAX-RS 注释?

java - lastindexof() 和十六进制 0x1A

java - 如何使用 JPA/Hibernate 持久保存声明具有几个整数的固定大小数组的字段的实体

java - 在 Spring 配置中使用时间戳

java - spring mvc - 客户端发送的请求在语法上不正确

java - 有什么方法可以让我的 JFrame 居中吗?

python - 如何访问存储为数据帧中的列的集合计数器的元素以在 CountVectorizer 中使用