java遍历map获取key和value
时间: 2023-05-22 19:06:27 浏览: 129
详解JAVA里面获取map的key和value的方法
5星 · 资源好评率100%
Sure, here's an example Java code to loop through a Map and print its keys and values:
```
Map<String, Integer> map = new HashMap<String, Integer>(); // create a Map
map.put("apple", 1); // add some key-value pairs
map.put("banana", 2);
map.put("cherry", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) { // loop through entries of the Map
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " -> " + value); // print the key-value pair
}
```
This code uses a for-each loop to iterate through the entries of the Map, and uses the `getKey()` and `getValue()` methods of the Map.Entry interface to retrieve the key and value of each entry. Hope this helps!
阅读全文