Java TreeMap Class Methods with Examples

In this article, we will learn TreeMap class methods with examples. TreeMap is A Red-Black tree based NavigableMap implementation.
The entries in a TreeMap are always sorted based on the natural ordering of the keys, or based on a custom Comparator that you can provide at the time of creation of the TreeMap.

What Will We Learn?

  1. Overview of TreeMap class
  2. Create a TreeMap Example
  3. TreeMap Sorting Order Example(Ascending Order)
  4. TreeMap with a custom Comparator (Descending Order)
  5. Accessing the entries of a TreeMap

1. Overview of TreeMap class

Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in sorted order.
The important points about Java TreeMap class are:
  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have a null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.

2. Create a TreeMap Example

// Creating a TreeMap
TreeMap<String, String> fileExtensions  = new TreeMap<>();

// Adding new key-value pairs to a TreeMap
fileExtensions.put("python", ".py");
fileExtensions.put("c++", ".cpp");
fileExtensions.put("kotlin", ".kt");
fileExtensions.put("golang", ".go");
fileExtensions.put("java", ".java");

// Printing the TreeMap (Output will be sorted based on keys)
System.out.println(fileExtensions);
Output:
{c++=.cpp, golang=.go, java=.java, kotlin=.kt, python=.py}

3. TreeMap Sorting Order Example(Ascending Order)

In this example, the elements are sorted in natural ordering.
public class MapInterfaceTreeSetImpl {
    public static void main(String[] args) {
    treeMapDemo();
 }

 // maintain keys in ascending order.
 private static void treeMapDemo() {
     // Constructs a new, empty tree map, using the natural ordering of its
     // keys
      Map<String, String> treeMap = new TreeMap<>();
      treeMap.put("key1", "value1");
      treeMap.put("key3", "value3");
      treeMap.put("key2", "value2");
      treeMap.put("key0", "value0");

      // loop linkedHahMap using java 8 forEach method
      treeMap.forEach((k, v) -> {
      System.out.println(k);
      System.out.println(v);
  });

     // loop linkedHahMap using before java 8 forEach method
     for (Entry pair : treeMap.entrySet()) {
         System.out.println(pair.getKey());
         System.out.println(pair.getValue());
     }
   }
}
Output:
key0
value0
key1
value1
key2
value2
key3
value3

4. TreeMap with a custom Comparator (Descending Order)

This example demonstrates how to create a TreeMap with a custom comparator that orders the TreeMap entries in the descending order of keys -
// Creating a TreeMap with a Custom comparator (Descending order)
SortedMap<String, Integer> numberWordMapping = new TreeMap<>(Comparator.reverseOrder());
// Adding new key-value pairs to a TreeMap
numberWordMapping.put("one", 1);
numberWordMapping.put("two", 2);
numberWordMapping.put("three", 3);
numberWordMapping.put("five", 5);
numberWordMapping.put("four", 4);

// Printing the TreeMap (The keys will be sorted based on the supplied
// comparator)
System.out.println(numberWordMapping);
Output:
{two=2, three=3, one=1, four=4, five=5}
Note that the keys are sorted in descending order.

5. Accessing the entries of a TreeMap

Find the size of a TreeMap.
TreeMap<Integer, String> users = new TreeMap<>();
users.put(1, "Ramesh");
// Finding the size of a TreeMap
System.out.println("Total number of users: " + users.size());
Check if a given key exists in a TreeMap.
TreeMap<Integer, String> users = new TreeMap<>();

users.put(1003, "A");
users.put(1001, "B");
users.put(1002, "C");
users.put(1004, "D");
// Check if a given key exists in a TreeMap
Integer id = 1004;
if(users.containsKey(id)) {
    // Get the value associated with a given key in a TreeMap
    String name = users.get(id);
    System.out.println("user with id " + id + " : " + name);
} else {
    System.out.println("user does not exist with id : " + id);
}
Retrieve the first entry in the TreeMap.
TreeMap<Integer, String> users = new TreeMap<>();

users.put(1003, "A");
users.put(1001, "B");
users.put(1002, "C");
users.put(1004, "D");
// Find the first entry
System.out.println("First entry in users map : " + users.firstEntry());
Retrieve the last entry in the TreeMap.
TreeMap<Integer, String> users = new TreeMap<>();

users.put(1003, "A");
users.put(1001, "B");
users.put(1002, "C");
users.put(1004, "D");
// Find the last entry
System.out.println("Last entry in users map : " + users.lastEntry());
Retrieve the entry whose key is just lower than the given key.
TreeMap<Integer, String> users = new TreeMap<>();

users.put(1003, "A");
users.put(1001, "B");
users.put(1002, "C");
users.put(1004, "D");
// Find the entry whose key is just less than the given key
Map.Entry<Integer, String> users = users.lowerEntry(1002);
Retrieve the entry whose key is just higher than the given key.
TreeMap<Integer, String> users = new TreeMap<>();

users.put(1003, "A");
users.put(1001, "B");
users.put(1002, "C");
users.put(1004, "D");
// Find the entry whose key is just higher than the given key
Map.Entry<Integer, String> usersEx = users.higherEntry(1002);

Further Learning

Comments