import java.util.Map; import java.util.HashMap; public class Example { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } }
import java.util.Map; import java.util.TreeMap; public class Example { public static void main(String[] args) { MapThis example creates a TreeMap object to store key-value pairs. It then adds two entries using the put() method. The entries are automatically sorted by key. Finally, it uses a for-each loop to print each entry in the map. Both examples use the Map.Entry interface to represent the key-value pairs. This interface is part of the java.util package library.map = new TreeMap<>(); map.put(3, "apple"); map.put(1, "banana"); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } }