Java 8 threads adding values ​​from two or more lists

I am trying to get into Java 8 and get my head around threads and lambda to solve various problems and am stuck on this particular one, which I usually use forEach and store values ​​in Map for solution.

How could you write code to get the expected list using 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 = ... 
+5
source share
2 answers

In fact, this is not how you hope. The closest thing you could probably get would be

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

... but there is no "zip" operation in the streams, mainly because two different streams may have backup delimiters that break up at different points, so you cannot align them correctly.

+6
source

JDK does not provide a zip API. But this can be done using the third AbacusUtil library:

 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 am a developer of AbacusUtil.

+2
source

Source: https://habr.com/ru/post/1213644/


All Articles