java – How should we handle the jdk8 stream for null values

The current thinking seems to be to “tolerate” nulls, ie to allow them in general, although some operations are less tolerant and may end up launching NPE. You see discussion of null on the Lambda Libraries Expert Group mailing list, specifically this message . The consensus on option no. 3 (with a notable objection from Doug Lea). So yes, the OP’s concern about pipelines exploding with NPE is valid.

It’s not for nothing that Tony Hoare referred to nulls as “Billion Dollar Mistake” Dealing with nulls is a real pain. Even with classic collections (without considering lambdas or streams) nulls are problematic. How fge mentioned in a comment, some collections allow null values ​​and others do not. With collections that allow null, this introduces ambiguity in the API. For example, with Map.get () , a null value indicates that the key is present and its value is null or that the key is absent. Extra work needs to be done to clear up these cases.

The usual use of null is to indicate the absence of a value. The approach to address this proposed for Java SE 8 is to introduce a new one Java.util.Optional type, which encapsulates the presence / absence of a value, along with the behaviors of providing a default value, throwing an exception or calling a function, etc. if the value is absent. Optional it is only used by the new APIs, however, everything else in the system still has to tolerate the possibility of null.

My advice is to avoid actual null references to the maximum extent possible. It is difficult to see from the example given how there could be a “null” otter. But if one were needed, the OP’s suggestions to filter out null values ​​or map them to a sentinel object ( Null Object Pattern ) are great approaches.

Leave a comment