简体   繁体   English

Java 8流for循环

[英]Java 8 stream for-loop

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. 我是Java 8 Streams的新手,并希望将以下代码块转换为Java 8的Stream方式来做同样的事情。

Edit : Updates the class-names to be less confusing. 编辑 :更新类名称以减少混淆。 (Removed Foo, Bar, Baz...) (删除了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 所有帮助和解释表示赞赏

You can do it with flatMap : 你可以用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. 由于objects.get(1).getObjects()似乎返回List<Object> ,因此需要objects.get(1).getObjects() To be safe, you can also add a filter that makes sure the type of the Object s is indeed BarBO prior to the cast : 为了安全起见,您还可以添加一个过滤器,以确保在BarBO之前Object的类型确实是BarBO

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: 考虑你的类(在你提供的示例中并假设它至少编译),我真的不明白为什么flatMap两次不起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM