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

2019-02-04 03:52发布

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?

8条回答
霸刀☆藐视天下
2楼-- · 2019-02-04 04:20

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);
查看更多
爷的心禁止访问
3楼-- · 2019-02-04 04:22

A solution is already selected. However, I post this solution for those who want to use an alternative approach:

// use LinkedHashMap if you want to read values from the hashmap in the same order as you put them into it
private ArrayList<String> getMapValueAt(LinkedHashMap<String, ArrayList<String>> hashMap, int index)
{
    Map.Entry<String, ArrayList<String>> entry = (Map.Entry<String, ArrayList<String>>) hashMap.entrySet().toArray()[index];
    return entry.getValue();
}
查看更多
放荡不羁爱自由
4楼-- · 2019-02-04 04:22

You can do:

for(String key: hashMap.keySet()){
    for(String value: hashMap.get(key)) {
        // use the value here
    }
}

This will iterate over every key, and then every value of the list associated with each key.

查看更多
聊天终结者
5楼-- · 2019-02-04 04:25

HashMaps are not ordered, unless you use a LinkedHashMap or SortedMap. In this case, you may want a LinkedHashMap. This will iterate in order of insertion (or in order of last access if you prefer). In this case, it would be

int index = 0;
for ( Map.Entry<String,ArrayList<String>> e : myHashMap.iterator().entrySet() ) {
    String key = e.getKey();
    ArrayList<String> val = e.getValue();
    index++;
}

There is no direct get(index) in a map because it is an unordered list of key/value pairs. LinkedHashMap is a special case that keeps the order.

查看更多
一夜七次
6楼-- · 2019-02-04 04:28
for (Object key : data.keySet()) {
    String lKey = (String) key;
    List<String> list = data.get(key);
}
查看更多
一夜七次
7楼-- · 2019-02-04 04:33

HashMaps don't keep your key/value pairs in a specific order. They are ordered based on the hash that each key's returns from its Object.hashCode() method. You can however iterate over the set of key/value pairs using an iterator with:

for (String key : hashmap.keySet()) 
{
    for (list : hashmap.get(key))
    {
        //list.toString()
    }
}
查看更多
登录 后发表回答