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

后端 未结 10 1336
鱼传尺愫
鱼传尺愫 2020-12-28 12:54

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

HashMap>

Basical

相关标签:
10条回答
  • 2020-12-28 13:25

    You can iterate over keys by calling map.keySet(), or iterate over the entries by calling map.entrySet(). Iterating over entries will probably be faster.

    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        List<String> list = entry.getValue();
        // Do things with the list
    }
    

    If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap.

    By the way, I'd recommend changing the declared type of the map to <String, List<String>>. Always best to declare types in terms of the interface rather than the implementation.

    0 讨论(0)
  • 2020-12-28 13:33

    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);
    
    0 讨论(0)
  • 2020-12-28 13:33

    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();
    }
    
    0 讨论(0)
  • 2020-12-28 13:35

    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.

    0 讨论(0)
提交回复
热议问题