Java Hashmap: How to get key from value?

前端 未结 30 1900
忘掉有多难
忘掉有多难 2020-11-22 02:14

If I have the value \"foo\", and a HashMap ftw for which ftw.containsValue(\"foo\") returns true, how can I

30条回答
  •  梦谈多话
    2020-11-22 03:06

    Use a thin wrapper: HMap

    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    
    public class HMap {
    
       private final Map> map;
    
       public HMap() {
          map = new HashMap>();
       }
    
       public HMap(final int initialCapacity) {
          map = new HashMap>(initialCapacity);
       }
    
       public boolean containsKey(final Object key) {
          return map.containsKey(key);
       }
    
       public V get(final Object key) {
          final Map entry = map.get(key);
          if (entry != null)
             return entry.values().iterator().next();
          return null;
       }
    
       public K getKey(final Object key) {
          final Map entry = map.get(key);
          if (entry != null)
             return entry.keySet().iterator().next();
          return null;
       }
    
       public V put(final K key, final V value) {
          final Map entry = map
                .put(key, Collections.singletonMap(key, value));
          if (entry != null)
             return entry.values().iterator().next();
          return null;
       }
    }
    

提交回复
热议问题