Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenience functions for operators in Java 8?

In Python, if I want to do a fold over the operation xor, I can write:

reduce(operator.xor, my_things, 0)

rather than the more cumbersome

reduce(lambda x, y: x^y, my_things, 0)

Is there anything like this in the new Java 8 functional features? e.g. to write something like this

myThings.reduce(0, Integer::xor)

rather than

myThings.reduce(0, (x, y) -> x ^ y)
like image 320
Patrick Collins Avatar asked Feb 03 '15 19:02

Patrick Collins


1 Answers

There's Integer#sum(int, int) which is used as you suggest in the package private IntPipeline, but no similar methods for other numerical operators.

@Override
public final int sum() {
    return reduce(0, Integer::sum);
}

You can define them yourself.

like image 179
Sotirios Delimanolis Avatar answered Sep 28 '22 02:09

Sotirios Delimanolis