The java.util.TreeMap class

TreeMap  is a hierarchical representation of data (key, value) in the form of a binary tree. Pairs in this class are sorted by key in ascending order.

As the class HashMap, the TreeMap implements the java.util.Map. The  Main difference between HashMap and TreeMap  is that HashMap is an unordered collection while TreeMap defaults to ascending order based on its keys. TreeMap is a non-synchronized collection, which means that it is not protected against concurrent access.

TreeMap example

Example 1:

In this example, Keys and values are stored in a TreeMap. To print the elements, you need to create an object Iterator then do the course with the loop  while.

import java.util.TreeMap; 
import java.util.Set;
import java.util.Iterator;
import java.util.Map;

public class parcours_treemap {

public static void main(String args[]) {

/* TreeMap declaration */
TreeMap tm = new TreeMap();

/*Add elements to TreeMap*/
tm.put(12, "val1");
tm.put(5, "val2");
tm.put(8, "val3");
tm.put(2, "val4");

/* Display content using Iterator */
Set set = tm.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mapentry = (Map.Entry)iterator.next();
System.out.print("key: "+ mapentry.getKey() + " +
"- value: "+mapentry.getValue()+"\n");
}

}
}
Executing this code returns this result:

key: 2 - value: val4
key: 5 - value: val2
key: 8 - value: val3
key: 12 - value: val1
We can see that the couples< key, value> are sorted in ascending order by keys.

Example 2:

To construct a TreeMap from another, you can invoke the putAll(Map)  which will restructure the tree as it is added.

import java.util.TreeMap; 

public class parcours {

public static void main(String args[]) {

/* TreeMap declaration */
TreeMap tm = new TreeMap();

/*Add elements to TreeMap*/
tm.put(12, "val1");
tm.put(5, "val2");
tm.put(8, "val3");
tm.put(2, "val4");

TreeMap tm2 = new TreeMap();
tm2.putAll(tm);

/*display a few pairs just to check */
System.out.print("key: 12" + " - value: "+tm2.get(12)+"\n");
System.out.print("key: 8" + " - value: "+tm2.get(8)+"\n");

/*first and last key*/
System.out.print("first key: "+tm2.firstKey()+" last key: "+tm2.lastKey());
}
}
Executing this code outputs this result:

key: 12 - value: val1
key: 8 - value: val3
first key: 2 last key: 12
References:
Documentation TreeMap
upmf-grenoble:TreeMap