Issue
I have a list of integers and I need to find the sum of its items. If the list contains any null
items, the result should be null
. My current implementation:
intList.stream().anyMatch(Objects::isNull) ? null : intList.stream().mapToInt(Integer::intValue).sum();
Can this be done with a single continuous stream? Is there an operation that terminates the stream if an item meets a condition?
Solution
As for your question "Is there an operation that terminates the stream if an item meets a condition?", Java 9 introduces Stream::takeWhile
which does this.
However, using this for your use case would result in a sum of everything before the null (not what you are expecting of actually returning a null). For your case, and being limited to the JDK, using the answer proposed by M A is the best (though it does not stop when it reaches a null).
The actual best way would be if there is a takeWhileInclusive
combined with the reduce operation. Unfortunately, takeWhileInclusive
does not exist in the JDK. However, Tagir Valeev, who is a committer in the JDK, has written a stream extension library (StreamEx) which has StreamEx::takeWhileInclusive
. It might be useful.
The following example, using that library, would step out with a null if null is encountered, or with the sum if it is not:
StreamEx.of(intList).takeWhileInclusive(Objects::nonNull)
.reduce(0, (a, b) -> a == null || b == null ? null : a + b);
Answered By - dajavax