java遍历hashmap的方法有哪些

267
2024/3/10 18:09:30
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,可以使用以下几种方法来遍历HashMap:

  1. 使用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());
}
  1. 使用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));
}
  1. 使用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);
}

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Java的abstract怎么使用