Why does a Spliterator <?> Define NONNULL as a characteristic?
The javadoc Spliterator (basically this is what really stands for Stream , if I understand things correctly) defines many characteristics that make sense, like SIZED , CONCURRENT , IMMUTABLE , etc.
But it also defines NONNULL ; why?
I would not care that the responsibility for this would be that if, for example, the developer tried the .sort() thread non SORTED , where there are null elements, he would rightfully welcome with NPE ...
But then this characteristic exists. What for? The javadoc Spliterator itself does not mention its actual use, as well as the package-info.java of the java.util.stream package ...
From the Spliterator documentation:
The separator also reports a set of
characteristics()its structure, source, and elements from amongORDERED,DISTINCT,SORTED,SIZED,NONNULL,IMMUTABLE,CONCURRENT, andSUBSIZED. They can be used by Spliterator clients to manage, specialize, or simplify computing.
Note that it does not mention the NullPointerException s warning. If you sort a Stream that can contain null values, you are responsible for providing a Comparator that can handle null s.
The second sentence also makes it clear that using these flags is only an option, not a requirement for “Spliterator clients,” which is not limited to using Stream s.
Thus, regardless of whether it is used by the current implementation of the Stream API, are there any opportunities to take advantage of knowledge of the NONULL ?
I think so. The implementation may go to specialized code for a non- null Spliterator to use null to represent a specific state, for example, missing values or an initial value before processing the first element, etc. If fact, the actual implementation code for Stream , which may contain null , is complex. But, of course, you always need to consider whether simplification justifies one instance of code duplication.
But sometimes simplification is as simple as knowing that there are no null values, meaning that you can use one of Concurrent… Collections that do not allow null s internally.
I found the following comments in enum StreamOpFlag code.
// The following Spliterator characteristics are not currently used but a // gap in the bit set is deliberately retained to enable corresponding // stream flags if//when required without modification to other flag values. // // 4, 0x00000100 NONNULL(4, ... // 5, 0x00000400 IMMUTABLE(5, ... // 6, 0x00001000 CONCURRENT(6, ... // 7, 0x00004000 SUBSIZED(7, ...