How to get values and keys from HashMap?
To get the values and keys from a HashMap in Java, you can use the values
and keySet
methods.
Here's an example of how you can use these methods to get the values and keys from a HashMap:
import java.util.HashMap;
import java.util.Set;
public class MapUtils {
public static void printMap(HashMap<String, Integer> map) {
for (int value : map.values()) {
System.out.println(value);
}
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println(key);
}
}
}
This code defines a printMap
method that takes a HashMap as an argument and prints the values and keys to the console.
To use this method, you can simply call it and pass in your HashMap as an argument:
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
MapUtils.printMap(map);
This will print the values and keys of the HashMap to the console:
1
2
3
A
B
C
I hope this helps! Let me know if you have any questions.