map and null values

Doug Lea dl at cs.oswego.edu
Thu Jan 3 03:42:32 PST 2013


On 01/03/13 05:41, Peter Levart wrote:
>
> On 01/02/2013 06:01 PM, Brian Goetz wrote:

>> Note that many existing Map implementations throw NPE when you try and
>> put a null key or value into it anyway.
>>
>>
> That's true, but the default *replace* method could do better for those
> (3rd party) Maps that allow null values.

To back up:

1. Everyone who has contemplated the issue sees that allowing
null elements in Stream API methods is a questionable idea.
Some of us think that we should bite the bullet now and
either not permit them or always ignore them. But the consensus
is to instead say in effect that any element operation involving
nulls is free to do anything it likes (use them, ignore them,
or blow up).

2. Because Maps often feed and are fed by streams, and because
parallel stream operations require concurrent maps, and because
the required concurrent map operations cannot accept nulls
(not because of meanness, but correctness), it is especially
questionable to allow them. But we took the same tactic as (1):
The added stream-support Map methods don't strictly forbid nulls,
they just don't don't do what some people who use null values
would like.

Moral: If you'd like to use new JDK8 stream/collection/map
features, it would be a good idea to get rid of your nulls now.
Otherwise you are at the mercy of all the particular policies
of all the methods reachable from stream operations.
This is not really different than the current state of affairs.
For example, sorting collections with nulls always blows up but
finding them via contains() usually doesn't. But the uniformity
of the Stream API makes people realize just how fragile their
null-containing collections and maps really were.

-Doug






More information about the lambda-dev mailing list