简体   繁体   中英

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

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.

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

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

如果您想要单个键的多个值,请考虑使用阵列列表的HashTable。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM