使用Java 8流迭代两个列表 [英] Iterating over two lists using Java 8 streams

查看:126
本文介绍了使用Java 8流迭代两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java 8流中编写以下内容?

How can I write the following in Java 8 streams?

int total = 0;
  for (ObjectA obja : rootObj.getListA()) {
    for (ObjectB objb : obja.getListB()) {
        total += objb.getCount() * obja.getCount();
    }
   }

return total;


推荐答案

转换嵌套 for 循环到 API使用是通过 flatMap

The canonical solution for converting nested for loops to Stream API usage is via flatMap:

return rootObj.getListA().stream()
.flatMapToInt(objA->objA.getListB().stream()
                                   .mapToInt(objB->objB.getCount() * objA.getCount()))
.sum();

这允许您为每个内部迭代执行操作。但是,在求和的特殊情况下,您可以简化操作,因为无论您计算(a + b + c + d)还是(a + b)+(c + d):

This allows you to perform an operation for each inner iteration. However, in the special case of summing you may simplify the operation as it doesn’t matter whether you compute (a+b+c+d) or (a+b)+(c+d):

return rootObj.getListA().stream()
.mapToInt(objA->objA.getListB().stream()
                               .mapToInt(objB->objB.getCount() * objA.getCount()).sum())
.sum();

当我们记住基本的算术时,我们也应该记得(a * x)+(b * x)等于(a + b)* x ,换句话说,没有必要乘以 ListB 的每个项目,其计数为 objA ,因为我们也可以将该结果的总和加倍:

And when we are at remembering elementary arithmetics we should also recall that (a*x)+(b*x) is equal to (a+b)*x, in other words, there is no need to multiply every item of ListB with the count of objA as we can also just multiple the resulting sum with that count:

return rootObj.getListA().stream()
.mapToInt(objA->objA.getListB().stream().mapToInt(ObjectB::getCount).sum()*objA.getCount())
.sum();

这篇关于使用Java 8流迭代两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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