Java遍历Map集合的方法有以下几种:
- 使用entrySet()方法遍历:通过Map的entrySet()方法获取Map集合的所有键值对的Set视图,然后使用foreach循环遍历每个键值对。
示例代码:
for (Map.Entryentry : map.entrySet()) { K key = entry.getKey(); V value = https://www.yisu.com/ask/entry.getValue();>
- 使用keySet()方法遍历:通过Map的keySet()方法获取Map集合的所有键的Set视图,然后使用foreach循环遍历每个键,再根据键获取对应的值。
示例代码:
for (K key : map.keySet()) { V value = https://www.yisu.com/ask/map.get(key);>
- 使用values()方法遍历:通过Map的values()方法获取Map集合的所有值的Collection视图,然后使用foreach循环遍历每个值。
示例代码:
for (V value : map.values()) { // 处理值 }
- 使用Iterator迭代器遍历:通过Map的entrySet()方法获取Map集合的所有键值对的Set视图,然后使用Iterator迭代器遍历每个键值对。
示例代码:
Iterator> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); K key = entry.getKey(); V value = https://www.yisu.com/ask/entry.getValue();>