Java 8 stream for-loop

这一生的挚爱 提交于 2019-12-22 05:25:26

问题


Im new to Java 8 Streams and would like to convert following code-block to Java 8's Stream way of doing the same thing.

Edit: Updates the class-names to be less confusing. (Removed Foo, Bar, Baz...)

ArrayList<PriceList> priceLists = new ArrayList<PriceList>();

// I'm casting to a type-safe List from getObjects() 
// -which is a function I dont have access to. Is there a nice 
// solution to embed this in the stream-syntax?
List<PriceListGroup> distObjects = (List<PriceListGroup>) objects.get(1).getObjects();

for(PriceListGroup group : distObjects) {
    Set<Affiliate> affiliates = group.getAffiliates();
    for(Affiliate affiliate : affiliates) {
        priceLists.add(affiliate.getPriceList());
    }
}

All help & explanation appreciated


回答1:


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());



回答2:


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());


来源:https://stackoverflow.com/questions/29342659/java-8-stream-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!