可以使用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