Map implementation with duplicate keys

后端 未结 18 1966
暗喜
暗喜 2020-11-22 15:23

I want to have a map with duplicate keys.

I know there are many map implementations (Eclipse shows me about 50), so I bet there must be one that allows this. I know

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 15:52

    what about such a MultiMap impl?

    public class MultiMap extends HashMap> {
      private static final long serialVersionUID = 1L;
      private Map> innerMap = new HashMap<>();
    
      public Set put(K key, V value) {
        Set valuesOld = this.innerMap.get(key);
        HashSet valuesNewTotal = new HashSet<>();
        if (valuesOld != null) {
          valuesNewTotal.addAll(valuesOld);
        }
        valuesNewTotal.add(value);
        this.innerMap.put(key, valuesNewTotal);
        return valuesOld;
      }
    
      public void putAll(K key, Set values) {
        for (V value : values) {
          put(key, value);
        }
      }
    
      @Override
      public Set put(K key, Set value) {
        Set valuesOld = this.innerMap.get(key);
        putAll(key, value);
        return valuesOld;
      }
    
      @Override
      public void putAll(Map> mapOfValues) {
        for (Map.Entry> valueEntry : mapOfValues.entrySet()) {
          K key = valueEntry.getKey();
          Set value = valueEntry.getValue();
          putAll(key, value);
        }
      }
    
      @Override
      public Set putIfAbsent(K key, Set value) {
        Set valueOld = this.innerMap.get(key);
        if (valueOld == null) {
          putAll(key, value);
        }
        return valueOld;
      }
    
      @Override
      public Set get(Object key) {
        return this.innerMap.get(key);
      }
    
      @Override
      etc. etc. override all public methods size(), clear() .....
    
    }
    

提交回复
热议问题