HashMap to return default value for non-found keys?

后端 未结 14 2133
别跟我提以往
别跟我提以往 2020-11-27 14:05

Is it possible to have a HashMap return a default value for all keys that are not found in the set?

相关标签:
14条回答
  • 2020-11-27 14:06

    On java 8+

    Map.getOrDefault(Object key,V defaultValue)
    
    0 讨论(0)
  • 2020-11-27 14:08
    /**
     * Extension of TreeMap to provide default value getter/creator.
     * 
     * NOTE: This class performs no null key or value checking.
     * 
     * @author N David Brown
     *
     * @param <K>   Key type
     * @param <V>   Value type
     */
    public abstract class Hash<K, V> extends TreeMap<K, V> {
    
        private static final long serialVersionUID = 1905150272531272505L;
    
        /**
         * Same as {@link #get(Object)} but first stores result of
         * {@link #create(Object)} under given key if key doesn't exist.
         * 
         * @param k
         * @return
         */
        public V getOrCreate(final K k) {
            V v = get(k);
            if (v == null) {
                v = create(k);
                put(k, v);
            }
            return v;
        }
    
        /**
         * Same as {@link #get(Object)} but returns specified default value
         * if key doesn't exist. Note that default value isn't automatically
         * stored under the given key.
         * 
         * @param k
         * @param _default
         * @return
         */
        public V getDefault(final K k, final V _default) {
            V v = get(k);
            return v == null ? _default : v;
        }
    
        /**
         * Creates a default value for the specified key.
         * 
         * @param k
         * @return
         */
        abstract protected V create(final K k);
    }
    

    Example Usage:

    protected class HashList extends Hash<String, ArrayList<String>> {
        private static final long serialVersionUID = 6658900478219817746L;
    
        @Override
            public ArrayList<Short> create(Short key) {
                return new ArrayList<Short>();
            }
    }
    
    final HashList haystack = new HashList();
    final String needle = "hide and";
    haystack.getOrCreate(needle).add("seek")
    System.out.println(haystack.get(needle).get(0));
    
    0 讨论(0)
  • 2020-11-27 14:09

    In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found.

    0 讨论(0)
  • 2020-11-27 14:09

    Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g.,

    Map<String, String> map = new DefaultedMap<>("[NO ENTRY FOUND]");
    String surname = map.get("Surname"); 
    // surname == "[NO ENTRY FOUND]"
    

    You can also pass in an existing map if you're not in charge of creating the map in the first place.

    0 讨论(0)
  • 2020-11-27 14:10

    Not directly, but you can extend the class to modify its get method. Here is a ready to use example: http://www.java2s.com/Code/Java/Collections-Data-Structure/ExtendedVersionofjavautilHashMapthatprovidesanextendedgetmethodaccpetingadefaultvalue.htm

    0 讨论(0)
  • 2020-11-27 14:15

    It does this by default. It returns null.

    0 讨论(0)
提交回复
热议问题