如何使用Java 8从对象列表的列表字段获取列表?

huangapple go评论55阅读模式
英文:

How to get list from objects' list field with java 8?

问题

我获得了一个包含公司列表的经理模型。我需要从几个经理那里获取所有公司。现在我有这段代码:

List<Company> companies = managers.stream().map(Manager::getCompanies).collect(Collectors.toList());

我需要怎么修改才能得到正确的结果?

英文:

I get a Manager model which have List of Companies. I need to get all companies from few managers.
Now i have this code:

List&lt;Company&gt; companies = managers.stream().map(Manager::getCompanies).collect(Collectors.toList());

What i need to do to get it correct?

答案1

得分: 4

flatMap是你的朋友:

List<Company> companies = managers.stream().flatMap(m -> m.getCompanies().stream()).collect(Collectors.toList());

flatMap会将所有的公司放入一个列表中,而不是多个包含公司的列表。

英文:

FlatMap is your friend:

List&lt;Company&gt; companies = managers.stream().flatMap(m -&gt; m.getCompanies().stream()).collect(Collectors.toList());

Flat map will put all companies in one list instead having multiple lists with companies.

答案2

得分: 1

听起来你有一个List&lt;Manager&gt;,每个经理都有一个List&lt;Company&gt;,你想要获得属于这些经理子集的公司的新列表。如果这是你想要做的事情,并且你想要使用流来实现,那么你需要像这样:

List&lt;Company&gt; companies = managers.stream()
                                      .filter(/* 限制你想要的经理 */)
                                      .map(Manager::getCompanies) // 获取每个经理的列表
                                      .flatMap(Collection::stream) // 合并列表
                                      .collect(Collectors.toList());

如果你需要担心空值,你可以在.map()行之后添加.filter(Objects::nonNull)

英文:

It sounds like you have a List&lt;Manager&gt; and each one has a List&lt;Company&gt;, and you want to get a new list of companies that fall under some subset of those managers. If that is what you are trying to do, and you want to do it with streams, then you need something like this:

List&lt;Company&gt; companies = managers.stream().
                                  .filter(/* limit to managers you want */)
                                  .map(Manager::getCompanies) // get each manager&#39;s list
                                  .flatMap(Collection::stream) // combine the lists
                                  .collect(Collectors.tolist());

If you have to worry about nulls you can add .filter(Objects::nonNull) after the .map() line.

huangapple
  • 本文由 发表于 2020年9月16日 20:47:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63920400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定