java代码中,如何循环遍历map,获取key和value
时间: 2024-05-05 11:18:38 浏览: 18
可以使用for each循环遍历Map,代码如下:
```
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key: " + key + ", value: " + value);
}
```
这段代码可以循环遍历Map,获取每个键值对的Key和Value。
相关问题
java遍历map获取key和value
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!
java中如何获取遍历map中key和把value
遍历map中key的方法:
```java
Map<String, Integer> map = new HashMap<>();
// 添加键值对到map中
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
// 遍历map中的key
for (String key : map.keySet()) {
System.out.println(key);
}
```
输出结果:
```
key1
key2
key3
```
获取map中所有value的方法:
```java
Map<String, Integer> map = new HashMap<>();
// 添加键值对到map中
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
// 遍历map中的值
for (Integer value : map.values()) {
System.out.println(value);
}
```
输出结果:
```
1
2
3
```
同时获取key和value的方法:
```java
Map<String, Integer> map = new HashMap<>();
// 添加键值对到map中
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
// 遍历map中的键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
```
输出结果:
```
key1: 1
key2: 2
key3: 3
```