gpt4 book ai didi

java - 不使用flatMap实现flatMap效果

转载 作者:行者123 更新时间:2023-12-01 06:34:31 24 4
gpt4 key购买 nike

我有一个定义开发人员的类。

class Developer {
private final String name;
Set<String> skills = new HashSet<>();

public Developer(final String name, final String... skills) {
this.name = name;
for (final String skill : skills) {
this.skills.add(skill);
}
}
}

我正在创建一个开发人员列表。

List<Developer> developers = new ArrayList<>();
people.add(new Developer("Bill", "Javascript", "HTML", "CSS"));
people.add(new Developer("Bob", "Java", "OOP", "Agile"));
people.add(new Developer("Barry", "Data Mining", "Machine Learning", "R"));

现在我想提取一套集体技能。我使用 flatMap 执行此操作,如下所示:

 Set<String> skills = developers.stream().flatMap(dev -> dev.skills.stream()).collect(Collectors.toSet());

有没有办法通过Stream来做到这一点而不使用flatMap

最佳答案

编辑

无需在收集器内使用线程安全结构,因为 the documentation说:

When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.

<小时/>

flatMap 是正确的选择。很高兴知道您问题背后的动机。

实现相同结果的另一种方法是使用 collectors (如其他答案所述)。您还可以避免使用 map 并将所有内容放入收集器中,例如:

Set<String> skills = developers.stream()
.collect(
HashSet<String>::new,
(acum, dev) -> acum.addAll(dev.skills),
Set::addAll
);

关于java - 不使用flatMap实现flatMap效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40199958/

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