BinaryOpertor for List<Integer> to add the lists

Mani :

In previous question I asked previously Which FunctionalInterface should I use?

Now I was trying to add to List<Integer> and not just two Integers a and b, such that each index adds to the same index of another list.

I had previously

 BinaryOperator<Integer> binaryOperator = Integer::sum;

for adding two integers using binaryOperator.apply(int a,int b). Is there a similar way like

BinaryOperator<List<Integer>> binaryOperator = List<Integer>::sum;

and then get the result in List<Integer> cList?

Ousmane D. :

if you want to perform some computation on the elements at corresponding indices (in this specific case the summation) there's no need to use a BinaryOperator, instead use IntStream.range to generate the indices:

// generates numbers from 0 until list.size exclusive 
IntStream.range(0, list.size())....

// generates numbers from 0 until the minimum of the two lists exclusive if needed
IntStream.range(0, Math.min(list.size(), list2.size()))....

The common name for this type of logic is "zip"; i.e. when given two input sequences it produces an output sequence in which every two elements from the input sequences at the same position are combined using some function.

There's no built-in method in the standard library for this, but you can find some generic implementations here.

for example, using the zip method in the accepted answer of the linked post, you could simply do:

List<Integer> result = zip(f.stream(), s.stream(), (l, r) -> l + r).collect(toList());

or using method reference:

List<Integer> result = zip(f.stream(), s.stream(), Math::addExact).collect(toList());

where f and s are your list of integers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87894&siteId=1