java 的hashmap遍历
时间: 2023-05-21 18:04:09 浏览: 100
可以使用迭代器或者forEach循环来遍历HashMap。以下是使用迭代器遍历HashMap的示例代码:
```
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
```
使用forEach循环遍历HashMap的示例代码如下:
```
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
```
相关问题
java hashmap遍历
Java中HashMap的遍历可以使用迭代器或者forEach()循环来实现。具体代码如下:
使用迭代器遍历HashMap:
```
HashMap<String,String> map = new HashMap<>();
Iterator<Map.Entry<String,String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
String key = entry.getKey();
String value = entry.getValue();
// do something with key and value
}
```
使用forEach()循环遍历HashMap:
```
HashMap<String,String> map = new HashMap<>();
map.forEach((key, value) -> {
// do something with key and value
});
```
java HashMap 遍历
可以使用Iterator遍历HashMap中的键值对,代码如下:
```
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}
```
另外,也可以使用for-each循环遍历HashMap中的键或值,代码如下:
```
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for (String key : map.keySet()) {
System.out.println("Key: " + key);
}
for (String value : map.values()) {
System.out.println("Value: " + value);
}
```
阅读全文