在Java中,可以使用以下几种方法来遍历HashMap:
- 使用entrySet()方法遍历HashMap的键值对:
HashMap<String, Integer> map = new HashMap<>();map.put("A", 1);map.put("B", 2);for (Map.Entry<String, Integer> entry : map.entrySet()) {System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());}- 使用keySet()方法遍历HashMap的键:
HashMap<String, Integer> map = new HashMap<>();map.put("A", 1);map.put("B", 2);for (String key : map.keySet()) {System.out.println("Key: " + key + ", Value: " + map.get(key));}- 使用values()方法遍历HashMap的值:
HashMap<String, Integer> map = new HashMap<>();map.put("A", 1);map.put("B", 2);for (Integer value : map.values()) {System.out.println("Value: " + value);}上一篇:使用dbeaver要注意哪些事项
下一篇:c++中usleep的功能有哪些
java hashmap









