-Host OS: Windows10 Home ・ Guest OS: WSL2 Ubuntu20.04 LTS ・ VScode ver 1.44.2 ・ Openjdk 11.0.7
-Get each element of HashMap using the extended for statement. The statement is a bit more complicated than an array or list.
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("dog", 3);
map.put("Cat", 10);
map.put("rabbit", 5);
Use the ** keySet () ** method
for(String animal : map.keySet()) {
System.outprintln(animal);
}
Output result
Cat
rabbit
dog
(* HashMap is not guaranteed in order unlike arrays and lists)
Use the ** values () ** method. Note that it's not the valuesSet () method
for(Integer num : map.values()) {
System.out.println(num);
}
Output result
5
3
10
Use the ** entrySet () ** method.
for(Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
Output result
Cat:10
dog:3
rabbit:5
Recommended Posts