Why null key is not allowed in TreeMap?
TreeMap
does allow null keys. The default natural ordering comparator is the one that throws the exception.
From the documentation of TreeMap.put
:
NullPointerException
- if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
The easiest way to allow null values is to create the TreeMap
with a comparator like Comparator.nullsFirst(Comparator.naturalOrder())
or Comparator.nullsLast(Comparator.naturalOrder())