When using streams in Java, is it possible to use a method reference for arithmetic addition (rather than a 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.
On a more general but similar note, does every method/operation in Java have a method reference?
Yes you can use Integer.sum
,
stream.reduce(0, Integer::sum)
Or you can convert the stream to an IntStream
and just call sum
stream.mapToInt(Integer::intValue).sum();
You can use Math.addExact
stream.reduce(0, Math::addExact)
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.