gpt4 book ai didi

Java 8 分组并追加到一个集合

转载 作者:行者123 更新时间:2023-11-30 07:41:48 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com