Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashMap: How to get a key and value by index?

I am trying to use a HashMap to map a unique string to a string ArrayList like this:

HashMap<String, ArrayList<String>> 

Basically, I want to be able to access the keys by number, not by using the key's name. And I want to be able to access said key's value, to iterate over it. I'm imagining something like this:

for(all keys in my hashmap) {     for(int i=0; i < myhashmap.currentKey.getValue.size(); i++) {         // do things with the hashmaps elements     } } 

Is there an easy way to do this?

like image 246
Derek Avatar asked Oct 19 '10 23:10

Derek


People also ask

Can you access a HashMap by index?

HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.

How do you find the value of the map for a specific index?

Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object. Convert the entry set to an array using the toArray() method. And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method.

Can we get index in HashMap in Java?

You can't - a set is unordered, so there's no index provided.


1 Answers

Here is the general solution if you really only want the first key's value

Object firstKey = myHashMap.keySet().toArray()[0]; Object valueForFirstKey = myHashMap.get(firstKey); 
like image 85
dumonderic Avatar answered Oct 05 '22 17:10

dumonderic