温馨提示×

java遍历hashmap的方法有哪些

小亿
109
2024-03-14 18:09:30
栏目: 编程语言

在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); } 

0