Java 8 stream for-loop

让人想犯罪 __ 提交于 2019-12-05 06:36:47

You can do it with flatMap :

List<FooBO> list1 = objects.get(1).getObjects().stream()
                                  .flatMap (b -> b.getAffiliates().stream())
                                  .map(BazBo::getPriceList)
                                  .collect(Collectors.toList());

Edit :

Since objects.get(1).getObjects() seems to return a List<Object>, a cast is required. To be safe, you can also add a filter that makes sure the type of the Objects is indeed BarBO prior to the cast :

List<FooBO> list1 = objects.get(1).getObjects().stream()
                                  .filter (o -> (o instanceof BarBo))
                                  .map (o -> (BarBO)o)
                                  .flatMap (b -> b.getAffiliates().stream())
                                  .map(BazBo::getPriceList)
                                  .collect(Collectors.toList());

EDIT :

Here's an answer with the class names of the edited question:

List<PriceList> priceLists = 
    distObjects.stream()
               .flatMap (g -> g.getAffiliates().stream())
               .map(Affiliate::getPriceList)
               .collect(Collectors.toList());

Considering your classes (in the example that you provided and assuming it compiles at least), I don't really understand why flatMap two times would not work:

 List<BarBO> input = new ArrayList<>();

    List<FooBO> result = input.stream()
            .flatMap((BarBO token) -> {
                return token.getAffiliats().stream();
            })
            .flatMap((BazBO token) -> {
                return token.getPriceList().stream();
            })
            .collect(Collectors.toList());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!