英文:
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<Company> 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<Company> companies = managers.stream().flatMap(m -> m.getCompanies().stream()).collect(Collectors.toList());
Flat map will put all companies in one list instead having multiple lists with companies.
答案2
得分: 1
听起来你有一个List<Manager>
,每个经理都有一个List<Company>
,你想要获得属于这些经理子集的公司的新列表。如果这是你想要做的事情,并且你想要使用流来实现,那么你需要像这样:
List<Company> companies = managers.stream()
.filter(/* 限制你想要的经理 */)
.map(Manager::getCompanies) // 获取每个经理的列表
.flatMap(Collection::stream) // 合并列表
.collect(Collectors.toList());
如果你需要担心空值,你可以在.map()
行之后添加.filter(Objects::nonNull)
。
英文:
It sounds like you have a List<Manager>
and each one has a List<Company>
, 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<Company> companies = managers.stream().
.filter(/* limit to managers you want */)
.map(Manager::getCompanies) // get each manager'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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论