Using a TreeMap in Java

A TreeMap maintains key/value objects in sorted order by using a balanced red-black tree. A red-black tree is a balanced binary tree, meaning a parent node has maximum 2 children and as an entry is inserted, the tree is monitored as to keep it well-balanced. For more information about red-black trees, check out the sites below!

Keeping the binary tree balanced ensures the fast insertion, removal and lookup time of O(log n). Not as fast as a HashMap which is O(constant), but remember that the TreeMap has the advantage that the keys are in sorted order which opens up a lot of other capabilities.

Following example shows most of the useful methods in TreeMap.

Main.java:

import java.util.*;
import java.io.*;
    
public class Main 
{
   public static void main(String []args) throws Exception {
      String[] colors = { "black", "white", "blue", "green", 
                          "red", "yellow", "magenta", "cyan", 
                          "orange", "redorange",
                         "violet", "purple" };
      String[] rgbs = { "[0,0,0]", "[255,255,255]", "[0,0,255]", "[0,255,0]", 
                        "[255,0,0]", "[255,255,0]", "[255,0,255]", "[0,255,255]",
                        "[255,165,0]", "[255,69,0]", "[255,69,0]",
                        "[238,130,238]", "[160,32,240]" };
 
      TreeMap tm = new TreeMap();
 
      for (int i=0; i<colors.length; i++) {
         tm.put(colors[i], rgbs[i]);
      }
 
      // containsKey, checks existence of a key
      System.out.println("containsKey("magenta"):nt" + 
                                tm.containsKey("magenta") + "n");
 
      // get, gets the value given the key
      System.out.println("get("yellow"):nt" + tm.get("yellow") + "n");
 
      // put, puts a key/value pair in the TreeMap
      tm.put("greenblue", "[46,139,87]");
 
      // firstKey, returns key for first entry
      System.out.println("firstKey():nt" + tm.firstKey() + "n");
 
      // lastKey, returns key for last entry
      System.out.println("lastKey():nt" + tm.lastKey() + "n");
 
      // entrySet, returns Set with key/value pairs each stored in 
      // an object of type Map.Entry
      Set entrySet = tm.entrySet();
      System.out.println("entrySet():nt" + entrySet + "n");
 
      // keySet, returns Set containing all keys
      Set keySet = tm.keySet();
      System.out.println("keySet():nt" + keySet + "n");
 
      // values, returns Collection containing all values
      Collection values = tm.values();
      System.out.println("values():nt" + values + "n");
 
      // headMap, returns sorted map of entries that are < than specified argument
      SortedMap headMap = tm.headMap("purple");
      System.out.println("headMap("purple"):nt" + headMap + "n");
 
      // subMap, returns sorted submap of entries that appear between two arguments
      SortedMap subMap = tm.subMap("green", "redorange");
      System.out.println("subMap("green", "redorange"):nt" + subMap + "n");
 
      // tailMap, returns sorted map of entries that are > than specified argument
      SortedMap tailMap = tm.tailMap("purple");
      System.out.println("tailMap("purple"):nt" + tailMap + "n");
   }
}

outputs:

containsKey("magenta"):
	true
 
get("yellow"):
	[255,255,0]
 
firstKey():
	black
 
lastKey():
	yellow
 
entrySet():
	[black=[0,0,0], blue=[0,0,255], cyan=[0,255,255], green=[0,255,0], 
greenblue=[46,139,87], magenta=[255,0,255], orange=[255,165,0], purple=[
238,130,238], red=[255,0,0], redorange=[255,69,0], violet=[255,69,0], wh
ite=[255,255,255], yellow=[255,255,0]]
 
keySet():
	[black, blue, cyan, green, greenblue, magenta, orange, purple, red,
 redorange, violet, white, yellow]
 
values():
	[[0,0,0], [0,0,255], [0,255,255], [0,255,0], [46,139,87], [255,0,2
55], [255,165,0], [238,130,238], [255,0,0], [255,69,0], [255,69,0], [255
,255,255], [255,255,0]]
 
headMap("purple"):
	{black=[0,0,0], blue=[0,0,255], cyan=[0,255,255], green=[0,255,0],
 greenblue=[46,139,87], magenta=[255,0,255], orange=[255,165,0]}
 
subMap("green", "redorange"):
	{green=[0,255,0], greenblue=[46,139,87], magenta=[255,0,255], ora
nge=[255,165,0], purple=[238,130,238], red=[255,0,0]}
 
tailMap("purple"):
	{purple=[238,130,238], red=[255,0,0], redorange=[255,69,0], viole
t=[255,69,0], white=[255,255,255], yellow=[255,255,0]}