2
Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
ht.put(1,"student1");
ht.put(1,"student2");

How can I iterate through all values of "a single key"?

key:1 values: student1, student2

Sara
  • 2,308
  • 11
  • 50
  • 76

4 Answers4

5

A Hashtable doesn't store multiple values for a single key.

When you write ht.put(1, "student2"), it overwrites the value that goes with "1" and it is no longer available.

Jeanne Boyarsky
  • 12,156
  • 2
  • 49
  • 59
5

You need to use:

Hashtable<Integer, List<String>> ht = new Hashtable<Integer, List<String>>();

and add the new String value for a particular key in the associated List.

Having said that, you should use a HashMap instead of Hashtable. The later one is legacy class, which has been replaced long back by the former.

Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();

then before inserting a new entry, check whether the key already exists, using Map#containsKey() method. If the key is already there, fetch the corresponding list, and then add new value to it. Else, put a new key-value pair.

if (map.containsKey(2)) {
    map.get(2).add("newValue");
} else {
    map.put(2, new ArrayList<String>(Arrays.asList("newValue")); 
}

Another option is to use Guava's Multimap, if you can use 3rd party library.

Multimap<Integer, String> myMultimap = ArrayListMultimap.create();

myMultimap.put(1,"student1");
myMultimap.put(1,"student2");

Collection<String> values = myMultimap.get(1);
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Hashtable doesn't allow multiple values for a key. When you add a second value to a key, you're replacing the original value.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
1

If you want multiple values for a single key, consider using a HashTable of ArrayLists.

Zong
  • 6,160
  • 5
  • 32
  • 46