import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); System.out.println(key); // prints key1 then key2 } } }
import java.util.Map; import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { TreeMapThis example demonstrates how to iterate over a TreeMap and get the key of each Entry using the Entry.getKey() method. Package/Library: `java.util`treeMap = new TreeMap<>(); treeMap.put(1, "value1"); treeMap.put(2, "value2"); for (Map.Entry entry : treeMap.entrySet()) { Integer key = entry.getKey(); System.out.println(key); // prints 1 then 2 } } }