可以使用HashMap的entrySet()方法来获取所有键值对,并且通过循环遍历打印出每个键值对的内容。具体代码如下所示:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
当运行这段代码时,会输出HashMap中所有键值对的内容,如下所示:
Key: key1, Value: value1
Key: key2, Value: value2
Key: key3, Value: value3