
Hashmap Loop in Java
Got you! Let’s see how to loop through a HashMap in Java ?:
Quick Example: Create and Loop a HashMap
import java.util.HashMap;import java.util.Map;public class HashMapLoopExample { public static void main(String[] args) { // Create a HashMap HashMap<String, Integer> map = new HashMap<>(); // Add some key-value pairs map.put("Apple", 50); map.put("Banana", 30); map.put("Cherry", 20); // Loop through the HashMap for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } }}
Output:
Key: Apple, Value: 50Key: Banana, Value: 30Key: Cherry, Value: 20
Other Ways to Loop a HashMap:
Method | Code Example |
---|---|
Loop through keySet() | for (String key : map.keySet()) { System.out.println(key); } |
Loop through values() | for (Integer value : map.values()) { System.out.println(value); } |
Using forEach method (Java 8+) | map.forEach((key, value) -> System.out.println(key + " -> " + value)); |
Quick Summary:
entrySet()
: Loop over both keys and values.keySet()
: Loop over keys only.values()
: Loop over values only.forEach()
: Shortcut style introduced in Java 8.
Would you like me to show a small example of sorting the HashMap by keys or values too? ??
That's a cool trick with loops! ?