Java 8 streams adding values from two or more lists

百般思念 提交于 2021-02-19 01:33:19

问题


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.

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 = ...

回答1:


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

...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.




回答2:


JDK doesn't provide the 'zip' API. But it can be done with third library AbacusUtil:

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

List<Integer> sumVotes = Stream.zip(voterA, voterB, (a, b) -> a + b).toList();

Disclosure: I'm the developer of AbacusUtil.



来源:https://stackoverflow.com/questions/28592529/java-8-streams-adding-values-from-two-or-more-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!