Mapmap = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); System.out.println(key); // output: apple, banana, orange }
MapIn this example, we create a TreeMap and add three entries. Then we iterate over the Map using a for-each loop and print out each key and value using the getKey() and getValue() methods of the Entry interface. Package library: java.utilmap = new TreeMap<>(); map.put(1, "Monday"); map.put(2, "Tuesday"); map.put(3, "Wednesday"); for (Map.Entry entry : map.entrySet()) { int key = entry.getKey(); System.out.println("Day " + key + " is " + entry.getValue()); // output: Day 1 is Monday, Day 2 is Tuesday, Day 3 is Wednesday }