遍历HashMap集合中的元素可以使用以下方法:
使用entrySet()方法遍历:通过HashMap的entrySet()方法可以获取到键值对集合Set,然后通过迭代器或循环遍历Set中的每个键值对,获取键和值。HashMap<String, Integer> hashMap = new HashMap<>();// 添加元素到HashMaphashMap.put("A", 1);hashMap.put("B", 2);hashMap.put("C", 3);// 使用entrySet()方法遍历HashMapfor(Map.Entry<String, Integer> entry : hashMap.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());}使用keySet()方法遍历:通过HashMap的keySet()方法可以获取到键的集合Set,然后通过迭代器或循环遍历Set中的每个键,获取对应的值。HashMap<String, Integer> hashMap = new HashMap<>();// 添加元素到HashMaphashMap.put("A", 1);hashMap.put("B", 2);hashMap.put("C", 3);// 使用keySet()方法遍历HashMapfor(String key : hashMap.keySet()) { Integer value = hashMap.get(key); System.out.println("Key: " + key + ", Value: " + value);}使用forEach()方法遍历:Java 8及以上版本可以使用forEach()方法结合Lambda表达式遍历HashMap。HashMap<String, Integer> hashMap = new HashMap<>();// 添加元素到HashMaphashMap.put("A", 1);hashMap.put("B", 2);hashMap.put("C", 3);// 使用forEach()方法遍历HashMaphashMap.forEach((key, value) -> { System.out.println("Key: " + key + ", Value: " + value);}); 

