Java 8流从两个或多个列表中添加值 [英] Java 8 streams adding values from two or more lists

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

问题描述

我试图进入Java 8并开始解决流和lambda的问题,以解决各种问题,并被困在通常使用forEach并将值存储在Map中的特定问题上.

I am trying to get into Java 8 and get my head around streams and lambdas to solve various problems and got stuck on this specific one which I normally use a forEach and store the values in a Map to solve.

您将如何使用Java 8的新功能编写代码以获取期望的列表?

How would you write the code to get the expected list using the new features in Java 8 ?

List<Integer> voterA = Arrays.asList(1,2,3,4,5);
List<Integer> voterB = Arrays.asList(1,2,3,4,5);
List<List<Integer>> votes = Arrays.asList(voterA, voterB);

// expected list = (2,4,6,8,10)
List<Integer> sumVotes = ...

推荐答案

那不是您所希望的真正可行的方法.您能获得的最接近的可能是

That one isn't really doable the way you're hoping. The closest you could get would probably be

IntStream.range(0, voterA.size())
    .mapToObj(i -> voterA.get(i) + voterB.get(i))
    .collect(toList());

...但是在流上没有"zip"操作,主要是因为两个不同的流可以具有在不同点处分离的后备分隔符,因此您无法正确地将它们对齐.

...but there's no "zip" operation on streams, largely because two different streams can have backing spliterators that split at different points, so you can't line them up properly.

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

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