简体   繁体   中英

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? eg to write something like this

myThings.reduce(0, Integer::xor)

rather than

myThings.reduce(0, (x, y) -> x ^ y)

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.

Yes, you can use the :: method reference operator on any static or instance method in place of a functional interface (lambda). I don't think there is one for Integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM