java hashmap key iteration

2019-02-03 04:27发布

Is there any way to iterate through a java Hashmap and print out all the values for every key that is a part of the Hashmap?

6条回答
爷的心禁止访问
2楼-- · 2019-02-03 04:28
public class abcd {
    public static void main(String[] args)
    {
       Map<Integer, String> testMap = new HashMap<Integer, String>();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Entry<Integer, String> entry : testMap.entrySet()) {
            Integer key=entry.getKey();
            String value=entry.getValue();
        }
    }
}
查看更多
仙女界的扛把子
3楼-- · 2019-02-03 04:29

Java 8 added Map.forEach which you can use like this:

map.forEach((k, v) -> System.out.println("key=" + k + " value=" + v));

There's also replaceAll if you want to update the values:

map.replaceAll((k, v) -> {
    int newValue = v + 1;
    System.out.println("key=" + k + " value=" + v + " new value=" + newValue);
    return newValue;
});
查看更多
甜甜的少女心
4楼-- · 2019-02-03 04:31

Yes, you do this by getting the entrySet() of the map. For example:

Map<String, Object> map = new HashMap<String, Object>();

// ...

for (Map.Entry<String, Object> entry : map.entrySet()) {
    System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}

(Ofcourse, replace String and Object with the types that your particular Map has - the code above is just an example).

查看更多
做个烂人
5楼-- · 2019-02-03 04:33
hashmap.keySet().iterator()

use a for loop to iterate it.

then use hashmap.get(item) to get individual values,

Alternatively just use entrySet() for getting an iterator for values.

查看更多
家丑人穷心不美
6楼-- · 2019-02-03 04:35
for (Map.Entry<T,U> e : map.entrySet())
{
    T key = e.getKey();
    U value = e.getValue();
    .
    .
    .
}

In addition, if you use a LinkedHashMap as the implementation, you'll iterate in the order the key/value pairs were inserted. If that's not important, use a HashMap.

查看更多
可以哭但决不认输i
7楼-- · 2019-02-03 04:44

With for-each loop, use Map.keySet() for iterating keys, Map.values() for iterating values and Map.entrySet() for iterating key/value pairs.

Note that all these are direct views to the map that was used to acquire them so any modification you make to any of the three or the map itself will reflect to all the others too.

查看更多
登录 后发表回答