import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); String mapString = map.toString(); System.out.println("Map as String: " + mapString); } }
import java.util.Map; import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { MapThis example uses a TreeMap to store key-value pairs. The TreeMap is ordered based on the keys, so the output of the toString() method will be ordered based on the keys as well. The package library for the Map interface is java.util.map = new TreeMap<>(); map.put("C", 3); map.put("A", 1); map.put("B", 2); String mapString = map.toString(); System.out.println("Map as String: " + mapString); } }