java遍历hashmap的方法有哪些
在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);
}
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:sqlserver错误18456怎么解决 下一篇:c++中exp函数的作用是什么
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。