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

后端 未结 10 1337
鱼传尺愫
鱼传尺愫 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:14

    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> e : myHashMap.iterator().entrySet() ) {
        String key = e.getKey();
        ArrayList 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.

提交回复
热议问题