TreeMap is a part of the Java Collections Framework that stores elements in key-value pairs and keeps the keys automatically sorted.
TreeMap sorts keys using their natural ordering or by a custom Comparator provided at creation time.
// Demonstration of TreeMap in Java
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
// Creating a TreeMap
TreeMap map=new TreeMap<>();
// Adding elements to TreeMap
map.put(3,"Java");
map.put(1,"HTML");
map.put(2,"CSS");
// Displaying sorted TreeMap
System.out.println(map);
}
}
The output is sorted automatically by key:
{1=HTML, 2=CSS, 3=Java}
Add items (Key must be Number) to see them automatically sort!
descendingMap() for reverse order