在Java中,要遍历HashMap,可以使用以下几种方法:
- 使用keySet()和get()方法:
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { HashMapmap = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); for (String key : map.keySet()) { Integer value = https://www.yisu.com/ask/map.get(key);"Key: " + key + ", Value: " + value); } } }
- 使用entrySet()方法:
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { HashMapmap = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); Integer value = https://www.yisu.com/ask/entry.getValue();"Key: " + key + ", Value: " + value); } } }
- 使用Java 8的forEach()方法和lambda表达式:
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { HashMapmap = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value)); } }
以上三种方法都可以遍历HashMap,并输出键值对。选择哪种方法取决于你的需求和编码风格。