简体   繁体   English

3 个嵌套的 for-each 循环作为 Java Stream(或更好的并行流)

[英]3 nested for-each loops as Java Stream (or better parallel stream)

On the project I am currently working on, we have this construct of three nested for loops:在我目前正在进行的项目中,我们有三个嵌套 for 循环的结构:

List<OutputDataType> resultList = new ArrayList<>();

for (OrgStructureEntity product : products) {

       for (String region : regions) {

                for (SalesType salesType : SalesType.values()) {

                    resultList.addAll(new SalesRequest(getConnection(),
                            product.getProductMainGroup(), product.getSbu(), planYear, currentPeriod, region, salesType,
                            exchangeRates).calculateSalesKpis());
                }    
       }
}

products and regions are both Sets. product 和 region 都是 Sets。 resultList is an ArrayList with "OutputDataType" objects. resultList 是一个带有“OutputDataType”对象的 ArrayList。 The method calculateSalesKpis() also returns a list of "OutputDataType" objects.方法calculateSalesKpis() 还返回一个“OutputDataType”对象列表。 All these objects are supposed to be added to the resultList.所有这些对象都应该添加到 resultList 中。 I would like to do all this with parallel streams to make it faster, but I didn't get much further than this:我想用并行流来做这一切以使其更快,但我没有比这更进一步:

products.stream()
                .map(product -> regions.stream()
                        .map(region -> Arrays.stream(SalesType.values())
                                .map(salesType -> new SalesRequest(getConnection(),
                                        product.getProductMainGroup(), product.getSbu(), planYear, currentPeriod, region, salesType,
                                        exchangeRates).calculateSalesKpis())))
                .

I don't know how to put it all in the result list now and how to close the stream correctly.我现在不知道如何将其全部放入结果列表以及如何正确关闭流。 I hope you can help me :)我希望你可以帮助我 :)

In order to avoid working on Stream>, you need to flatten your nested Stream structure using the flatmap method before performing a collection:为了避免在 Stream> 上工作,您需要在执行集合之前使用flatmap方法展平嵌套的Stream结构:

products.stream()
  .flatMap(product -> regions.stream()
    .flatMap(region -> Arrays.stream(SalesType.values())
     .flatMap(salesType -> new SalesRequest(getConnection(),
       product.getProductMainGroup(), product.getSbu(), planYear, currentPeriod, region, salesType, exchangeRates).calculateSalesKpis().stream())))
  .collect(Collectors.toList())

            .

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

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