TreeMap in Java
TreeMap is Red-Black tree based NavigableMap implementation. It is sorted according to the natural ordering of its keys.
Example
import java.util.Map; import java.util.TreeMap; public class Detective { public static void main(String[] args) { //The entries in a TreeMap are always sorted based on the natural ordering of the keys Map<Integer, String> statements = new TreeMap<Integer, String>(); // Inserting statements into the map statements.put(5, "shouting"); statements.put(1, "fight"); statements.put(7, "fleeing"); statements.put(9, "gunshot"); statements.put(15, "panic"); statements.put(3, "anger"); statements.put(8, "shouting"); // printing the already sorted map printStatements(statements); } public static void printStatements(Map<Integer, String> map) { for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println( "Key : " + entry.getKey() + " Value : " +entry.getValue()); } } }
Output
Key : 1 Value : fight Key : 3 Value : anger Key : 5 Value : shouting Key : 7 Value : fleeing Key : 8 Value : shouting Key : 9 Value : gunshot Key : 15 Value : panic