Sara
Sara

Reputation: 2436

iterate through all the values of a key in hashtable java

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

Upvotes: 2

Views: 2684

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213261

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);

Upvotes: 5

Zong
Zong

Reputation: 6230

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

Upvotes: 1

Steve P.
Steve P.

Reputation: 14699

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

Upvotes: 1

Jeanne Boyarsky
Jeanne Boyarsky

Reputation: 12266

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.

Upvotes: 5

Related Questions