在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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/934458.html