gpt4 book ai didi

java - 将 List 流转换为单个 Container

转载 作者:太空狗 更新时间:2023-10-29 23:03:06 25 4
gpt4 key购买 nike

考虑以下 WorkExperience类:

public class WorkExperience {
private int year;
private List<Skills> skill;

public WorkExperience(int year, List<Skills> skill) {
this.year = year;
this.skill = skill;
}
//getter setter
}

public class Skills {
private String skills;

public Skills(String skills) {
this.skills = skills;
}

@Override
public String toString() {
return "Skills [skills=" + skills + "]";
}
}

假设我想按年份对我的技能进行分组,我们可以这样做 groupBy按年份:

public static void main(String[] args) {

List<Skills> skillSet1 = new ArrayList<>();
skillSet1.add(new Skills("Skill-1"));
skillSet1.add(new Skills("Skill-2"));
skillSet1.add(new Skills("Skill-3"));

List<Skills> skillSet2 = new ArrayList<>();
skillSet2.add(new Skills("Skill-1"));
skillSet2.add(new Skills("Skill-4"));
skillSet2.add(new Skills("Skill-2"));


List<Skills> skillSet3 = new ArrayList<>();
skillSet3.add(new Skills("Skill-1"));
skillSet3.add(new Skills("Skill-9"));
skillSet3.add(new Skills("Skill-2"));

List<WorkExperience> workExperienceList = new ArrayList<>();
workExperienceList.add(new WorkExperience(2017,skillSet1));
workExperienceList.add(new WorkExperience(2017,skillSet2));
workExperienceList.add(new WorkExperience(2018,skillSet3));

Map<Integer, Set<List<Skills>>> collect = workExperienceList.stream().collect(
Collectors.groupingBy(
WorkExperience::getYear,
Collectors.mapping(WorkExperience::getSkill, Collectors.toSet())
)
);
}

groupBy正在返回:Map<Integer, Set<List<Skills>>>
但我需要的是:Map<Integer, Set<Skills>>

如何将List流转为单个Container?

最佳答案

仅使用 Java 8 功能的 flatMapping 的替代方法是

Map<Integer, Set<Skills>> map = workExperienceList.stream()
.collect(Collectors.toMap(
WorkExperience::getYear,
we -> new HashSet<>(we.getSkill()),
(s1, s2)-> { s1.addAll(s2); return s1; }));

你可以稍微优化一下

Map<Integer, Set<Skills>> map = workExperienceList.stream()
.collect(Collectors.toMap(
WorkExperience::getYear,
we -> new HashSet<>(we.getSkill()),
(s1, s2) -> {
if(s1.size() > s2.size()) { s1.addAll(s2); return s1; }
else { s2.addAll(s1); return s2; }
}));

关于java - 将 List 流转换为单个 Container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307704/

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