Search code examples
javanulltreemap

TreeMap allowing null key


I am searching for a TreeMap that allows one null key. What I need is a sorted Map<Long,String> where I can insert one null key representing the default value: If the map does not contain the specified key, the value associated with the null key will be used.
I have been searching for this map for quite a while, but all I found was TreeMap which does not allow null keys.

Does Java have any sorted maps that allow one null key?


Solution

  • You could perhaps write your own. Something like this might work with some tinkering.

    static class MapWithDefault<K, V> extends TreeMap<K, V> {
        private V dflt;
    
        @Override
        public V get(Object key) {
            V v = super.get(key);
            return v == null ? dflt : v;
        }
    
        @Override
        public V put(K key, V value) {
            if (key == null) {
                V was = dflt;
                dflt = value;
                return was;
            }
            return super.put(key, value);
        }
    
        public void setDflt(V dflt) {
            this.dflt = dflt;
        }
    }