Java 8流for循环 [英] Java 8 stream for-loop

查看:182
本文介绍了Java 8流for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java 8 Streams的新手,并希望将以下代码块转换为Java 8的Stream方式来做同样的事情。

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.

编辑:更新类名以减少混淆。 (删除了Foo,Bar,Baz ......)

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

推荐答案

您可以使用 flatMap

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

编辑:

objects.get(1).getObjects()似乎返回 List< Object> ,需要强制转换。为了安全起见,您还可以添加一个过滤器,以确保 Object 的类型确实是 BarBO 之前演员:

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

编辑:

这是一个答案已编辑问题的类名:

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

这篇关于Java 8流for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆