简体   繁体   English

是否有算术加法的Java方法参考?

[英]Is there a Java method reference for arithmetic addition?

When using streams in Java, is it possible to use a method reference for arithmetic addition (rather than a lambda)?在 Java 中使用流时,是否可以使用方法引用进行算术加法(而不是 lambda)?

At the moment (to sum the contents of a stream) I am using stream.reduce(0, (x, y) -> x + y) , but I would like to use something like stream.reduce(0, Math::add) , if it exists.目前(对流的内容求和)我正在使用stream.reduce(0, (x, y) -> x + y) ,但我想使用类似stream.reduce(0, Math::add) ,如果它存在。


On a more general but similar note, does every method/operation in Java have a method reference?更一般但类似的是,Java 中的每个方法/操作都有一个方法引用吗?

Yes you can use Integer.sum ,是的,你可以使用Integer.sum

stream.reduce(0, Integer::sum)

Or you can convert the stream to an IntStream and just call sum或者您可以将流转换为IntStream并调用sum

stream.mapToInt(Integer::intValue).sum();

You can use Math.addExact您可以使用Math.addExact

stream.reduce(0, Math::addExact)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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