Printing HashMap In Java
To print the contents of a HashMap in Java, you can use the entrySet()
method to get a set of key-value pairs and then iterate over the set to print the keys and values.
Here's an example of how to print a HashMap in Java:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 35);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
This will output the following:
Alice: 25 Bob: 30 Charlie: 35
Alternatively, you can use the keySet()
method to get a set of keys and then use the get()
method to get the values for each key.
Here's an example of how to do this:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
map