Multi-valued hashtable in Java

前端 未结 13 1886
余生分开走
余生分开走 2020-12-06 09:41

Is it possible to have multiple values for the same key in a hash table? If not, can you suggest any such class or interface which could be used?

相关标签:
13条回答
  • 2020-12-06 10:02

    Following code without Google's Guava library. It is used for double value as key and sorted order

    Map<Double,List<Object>> multiMap = new TreeMap<Double,List<Object>>();
    
    for( int i= 0;i<15;i++)
    {
        List<Object> myClassList = multiMap.get((double)i);
        if(myClassList == null)
        {
            myClassList = new ArrayList<Object>();
            multiMap.put((double) i,myClassList);
        }
        myClassList.add("Value "+ i);
    }
    
    List<Object> myClassList = multiMap.get((double)0);
    if(myClassList == null)
    {
        myClassList = new ArrayList<Object>();
        multiMap.put( (double) 0,myClassList);
    }
    myClassList.add("Value Duplicate");
    for (Map.Entry entry : multiMap.entrySet()) 
    {
      System.out.println("Key = " + entry.getKey() + ", Value = " +entry.getValue());
    }
    
    0 讨论(0)
  • 2020-12-06 10:04

    Values of a hash table is Object so you can store a List

    0 讨论(0)
  • 2020-12-06 10:04

    Simple. Instead of Hashtable<Key, Value>, use Hashtable<Key, Vector<Value>>.

    0 讨论(0)
  • 2020-12-06 10:06

    You need to use something called a MultiMap. This is not strictly a Map however, it's a different API. It's roughly the same as a Map<K, List<V>>, but you wont have methods like entrySet() or values().

    0 讨论(0)
  • 2020-12-06 10:10

    Rather than give yet another multipmap answer, I'll ask why you want to do this?

    Are the multiple values related? If yes, then it's probably better that you create a data structure to hold them. If no, then perhaps it's more appropriate to use separate maps.

    Are you keeping them together so that you can iterate them based on the key? You might want to look for an alternative indexing data structure, like a SkipList.

    0 讨论(0)
  • 2020-12-06 10:14

    Just make your own:

    Map<Object, List<Object>> multiMap = new HashMap<Object, List<Object>>();
    

    To add:

      public void add(String key, Object o) {
        List<Object> list;
        if (multiMap.containsKey(key)) {
          list = multiMap.get(key);
          list.add(o);
        } else {
          list = new ArrayList<Object>();
          list.add(o);
          multiMap.put(key, list);
        }
      }
    
    0 讨论(0)
提交回复
热议问题