Java The TreeMap Class

TreeMap class implements Map interface similar to HashMap class. It maintains its entries in ascending order, sorted according to the keys natural ordering, or according to a Comparator depends on constructor argument. Unlike LinkedHashMap and HashMap, TreeMap does not use hashing for storing keys. It uses a data structure called Red-Black tree.
Java TreeMap and Red-Black tree algorithm

A red–black tree is a kind of self-balancing binary search tree which has the following red-black properties:

1. Every node is either red or black. 2. Root of tree is always black. 3. Every leaf (NULL) is black. 4. If a node is red, then both its children are black. 5. Every path from root to a NULL node has same number of black nodes.
How to Java TreeMap TreeMap implementation is not synchronized . If multiple threads access a TreeMap concurrently, and at least one of the threads modifies the TreeMap structurally, it should be synchronized externally. The TreeMap class is perfect for traversing the keys in a sorted order. The keys can be sorted using the Comparable interface or the Comparator interface. You can specify Sorting order while Creating TreeMap by providing an explicit Comparator to TreeMap. Moreover, it provides the methods firstKey() and lastKey() for returning the first and last keys in the map, and headMap(toKey) and tailMap(fromKey) for returning a portion of the map whose keys are less than toKey and greater than or equal to fromKey.

The following Java program illustrates several of the methods supported by this TreeMap collection Framework:

import java.util.*; class TestClass { public static void main (String[] args) throws java.lang.Exception { //How to Create TreeMap? TreeMap <Integer,String> days = new TreeMap <Integer,String>(); //How to Add Key/Value pairs in TreeMap? days.put(1,"Sunday"); days.put(2,"Monday"); days.put(3,"Tuesday"); days.put(4,"Wednesday"); days.put(5,"Thursday"); days.put(6,"Friday"); days.put(7,"Saturday"); //How to iterate through TreeMap? for(Map.Entry m:days.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } //How to remove specific item from TreeMap? days.remove(3); Set<Map.Entry<Integer,String>> set = days.entrySet(); for (Map.Entry<Integer,String> sg : set) { System.out.println("Key :"+sg.getKey() + " Value :"+days.get(sg.getKey())); } //How to search a key in TreeMap? Integer key=4; if(days.containsKey(key)){ System.out.println("Key " + key + " found"); }else{ System.out.println("Key " + key+ " does not exist"); } //How to get Key from its Value in TreeMap? Integer iKey= null; String value="Monday"; for(Map.Entry entry: days.entrySet()){ if(value.equals(entry.getValue())){ iKey = (Integer)entry.getKey(); break; //breaking because its one to one map } } System.out.println("Found Key : "+ iKey +" value: " + value); //How remove all item from TreeMap? days.clear(); //How to find the size of TreeMap? System.out.println("After remove: "+ days.size()); } }