在Java中,可以使用迭代器或者forEach循环来遍历HashMap。以下是两种常用的遍历HashMap的方法:
使用迭代器遍历HashMap:HashMap<String, String> map = new HashMap<>();map.put("key1", "value1");map.put("key2", "value2");map.put("key3", "value3");Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());}使用forEach循环遍历HashMap:HashMap<String, String> map = new HashMap<>();map.put("key1", "value1");map.put("key2", "value2");map.put("key3", "value3");map.forEach((key, value) -> { System.out.println("Key: " + key + ", Value: " + value);});无论使用哪种方法,都可以遍历HashMap并输出其中的键值对。请根据具体的需求选择适合的遍历方法。


