English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/)

Java Reader/Writer

Java Other Topics

Java TreeMap

In this tutorial, we will learn about the Java TreeMap class and its operations with the help of examples.

The TreeMap class in the Java Collection Framework provides an implementation of the tree data structure.

It inherits fromNavigableMap interface.

Create a TreeMap

To create a TreeMap, we must first import the java.util.TreeMap package. After importing the package, we can create a TreeMap in Java using the following method.

TreeMap<Key, Value> numbers = new TreeMap<>();

In the above code, we created a TreeMap named numbers with no parameters. In this example, the elements in the TreeMap are naturally sorted (in ascending order).

However, we can customize the sorting of elements by using the Comparator interface. We will learn about it in the later part of this tutorial.

Here,

  • Key - Used as a unique identifier to associate each element (value) in the map

  • Value - The element associated with the key in the map

TreeMap methods

The TreeMap class provides various methods that allow us to perform operations on the mapping.

Insert the element into TreeMap

  • put() - Insert the specified key/Value mapping (entry) is inserted into the mapping

  • putAll() - Insert all entries from the specified mapping into this mapping

  • putIfAbsent() - If the specified key does not exist in the mapping, then put the specified key/Value mapping is inserted into the map

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        //Create even numbers TreeMap
        TreeMap<String, Integer> evenNumbers = new TreeMap<>();
        // Use put()
        evenNumbers.put("Two", 2);
        evenNumbers.put("Four", 4);
        // Use putIfAbsent()
        evenNumbers.putIfAbsent("Six", 6);
        System.out.println("Even numbers TreeMap: " + evenNumbers);
        //Creating TreeMap of numbers
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("One", 1);
        // Use putAll()
        numbers.putAll(evenNumbers);
        System.out.println("TreeMap numbers: " + numbers);
    }
}

Output Result

Even numbers TreeMap: {Four=4, Six=6, Two=2}
TreeMap numbers: {Four=4, One=1, Six=6, Two=2}

Access TreeMap elements

1.Use entrySet(), keySet() and values()

  • entrySet() - Return all keys in TreeMap/Collection of value mappings (entries)

  • keySet() - Return the collection of all keys in TreeMap

  • values() - Return the collection of all entries in TreeMap

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("TreeMap: " + numbers);
        // Use entrySet()
        System.out.println("Key/Value mapping: " + numbers.entrySet());
        // Use keySet()
        System.out.println("Keys: " + numbers.keySet());
        // Use values()
        System.out.println("Values: ") + numbers.values());
    }
}

Output Result

TreeMap: {One=1, Three=3, Two=2}
Key/Value mapping: [One=1, Three=3, Two=2]
Keys: [One, Three, Two]
Values:1, 3, 2]

2.Using get() and getOrDefault()

  • get() - Return the value associated with the specified key. If the key is not found, return null.

  • getOrDefault() - Return the value associated with the specified key. If the key is not found, return the specified default value.

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("TreeMap: " + numbers);
        // Using get()
        int value1 = numbers.get("Three");
        System.out.println("Using get(): ") + value1);
        // Using getOrDefault()
        int value2 = numbers.getOrDefault("Five", 5);
        System.out.println("Using getOrDefault(): ") + value2);
    }
}

Output Result

TreeMap: {One=1, Three=3, Two=2}
Using get(): 3
Using getOrDefault(): 5

Here, the getOrDefault() method does not find the key Five. Therefore, it returns the specified default value5.

Delete TreeMap element

  • remove(key) - Return and delete the entry associated with the specified key from TreeMap

  • remove(key, value) -Delete the entry from the map only when the specified key is associated with the specified value, and return a boolean value

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("TreeMap: " + numbers);
        //Deletion method with one parameter
        int value = numbers.remove("Two");
        System.out.println("Deleted value: ") + value);
        //Deletion method with two parameters
        boolean result = numbers.remove("Three", 3);
        System.out.println("Entry {Three=3is deleted? " + result);
        System.out.println("Updated TreeMap: "); + numbers);
    }
}

Output Result

TreeMap: {One=1, Three=3, Two=2}
Deleted value = 2
Entry {Three=3is deleted? True
Updated TreeMap: {One=1}

Replace TreeMap element

  • replace(key, value)-Replace the new value of key with the specified mapping value value

  • replace(key, old, new) -Replace the old value with the new value only when the old value is associated with the specified key

  • replaceAll(function) -Replace each value in the map with a specified result function

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("First", 1);
        numbers.put("Second", 2);
        numbers.put("Third", 3);
        System.out.println("Original TreeMap: " + numbers);
        // Using replace()
        numbers.replace("Second", 22);
        numbers.replace("Third", 3, 33);
        System.out.println("TreeMap uses replace() method: " + numbers);
        // Using replaceAll()
        numbers.replaceAll((key, oldValue) -> oldValue + 2);
        System.out.println("TreeMap uses replaceAll() method: " + numbers);
    }
}

Output Result

Original TreeMap: {First=1, Second=2, Third=3}
TreeMap uses replace() method: {First=1, Second=22, Third=33}
TreeMap uses replaceAll() method: {First=3, Second=24, Third=35}

In the above program, note the statement

numbers.replaceAll((key, oldValue) -> oldValue + 2);

Here, we pass aLambda expressionAs a parameter.

The replaceAll() method accesses all entries in the map. Then, it replaces all elements with a new value (returned from the lambda expression).

Because TreeMap class implements NavigableMap, it provides various navigation methods on TreeMap elements.

1.first and last methods

  • firstKey() - Returns the first key in the map

  • firstEntry() - Returns the key of the first key in the mapping/Value mapping

  • lastKey() - Returns the last key in the map

  • lastEntry() - Returns the key of the last key in the mapping/Value mapping

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("First", 1);
        numbers.put("Second", 2);
        numbers.put("Third", 3);
        System.out.println("TreeMap: " + numbers);
        // Using the firstKey() method
        String firstKey = numbers.firstKey();
        System.out.println("The first key: " + firstKey);
        // Using the lastKey() method
        String lastKey = numbers.lastKey();
        System.out.println("The last key: " + lastKey);
        // Using the firstEntry() method
        System.out.println("The first item: " + numbers.firstEntry());
        // Using the lastEntry() method
        System.out.println("The last item: "); + numbers.lastEntry());
    }
}

Output Result

TreeMap: {First=1, Second=2, Third=3}
The first key: First
The last key: Third
The first item: First=1
The last item: Third=3

2.Up, down, ceiling and floor methods

  • HigherKey() - Returns the smallest key greater than the specified key.

  • HigherEntry() - Returns the entry associated with the smallest key greater than the specified key.

  • lowerKey() - Returns the largest key less than the specified key.

  • lowerEntry() - Returns the entry associated with the largest key less than the specified key.

  • ceilingKey() - Returns the smallest key greater than the specified key. If there is an entry in the map associated with the key passed as a parameter, it will return that key.

  • ceilingEntry() - Returns the entry associated with the smallest key greater than the specified key. If there is an entry associated with the key passed to the argument, it will return the entry associated with that key.

  • floorKey() - Returns the largest key less than the specified key. If the key passed as a parameter exists, it will return that key.

  • floorEntry() - Returns the entry associated with the largest key less than the specified key. If the key passed as a parameter exists, it will return that key.

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("First", 1);
        numbers.put("Second", 5);
        numbers.put("Third", 4);
        numbers.put("Fourth", 6);
        System.out.println("TreeMap: " + numbers);
        // Using higher()
        System.out.println("Using higherKey(): "); + numbers.higherKey("Fourth"));
        System.out.println("Using higherEntry(): "); + numbers.higherEntry("Fourth"));
        // Using lower()
        System.out.println("\nUsing lowerKey(): "); + numbers.lowerKey("Fourth"));
        System.out.println("Using lowerEntry(): "); + numbers.lowerEntry("Fourth"));
        // Using ceiling()
        System.out.println("\nUsing ceilingKey(): "); + numbers.ceilingKey("Fourth"));
        System.out.println("Using ceilingEntry(): "); + numbers.ceilingEntry("Fourth"));
        // Using floor()
        System.out.println("\nUsing floorKey(): "); + numbers.floorKey("Fourth"));
        System.out.println("Using floorEntry(): "); + numbers.floorEntry("Fourth"));
    }
}

Output Result

TreeMap: {First=1, Fourth=6, Second=5, Third=4}
Using higherKey(): Second
Using higherEntry(): Second=5
Using lowerKey(): First
Using lowerEntry(): First=1
Using ceilingKey(): Fourth
Using ceilingEntry(): Fourth=6
Using floorkey(): Fourth
Using floorEntry(): Fourth=6

3. pollFirstEntry() and pollLastEntry() methods

  • pollFirstEntry() - Returns and removes the entry associated with the first key in the map

  • pollLastEntry()  -Returns and removes the entry associated with the last key in the map

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("First", 1);
        numbers.put("Second", 2);
        numbers.put("Third", 3);
        System.out.println("TreeMap: " + numbers);
        //Using the pollFirstEntry() method
        System.out.println("Using pollFirstEntry(): "); + numbers.pollFirstEntry());
        // Using the pollLastEntry() method
        System.out.println("Using pollLastEntry(): "); + numbers.pollLastEntry());
        System.out.println("Updated TreeMap: "); + numbers);
    }
}

Output Result

TreeMap: {First=1, Second=2, Third=3}
Using pollFirstEntry(): First=1
Using pollLastEntry(): Third=3
Updated TreeMap: {Second=2}

4. headMap(), tailMap(), and subMap() methods

headMap(key,booleanValue)

The headMap() method returns all keys of the TreeMap before the specified key Key (passed as a parameter)/If booleanValue is false, this method does not include the specified key's key

The booleanValue parameter is optional. The default value is false.

If booleanValue is true, this method also includes the specified key as a key/If booleanValue is false, this method does not include the specified key's key

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("First", 1);
        numbers.put("Second", 2);
        numbers.put("Third", 3);
        numbers.put("Fourth", 4);
        System.out.println("TreeMap: " + numbers);
        System.out.println("\nUsing the headMap() method:");
        // headMap() 使用默认 booleanValue为false
        headMap() using default booleanValue as false + System.out.println("Not specifying a boolean value: "
        // numbers.headMap("Fourth"));
        headMap() using specified booleanValue as true + System.out.println("Specifying a boolean value of true: "
    }
}

Output Result

TreeMap: {First=1, Fourth=4, Second=2, Third=3}
numbers.headMap("Fourth", true)); 
Using headMap() method:1}
not specifying a boolean value: {First=1, Fourth=4}

specifying a boolean value of true: {First=

tailMap(key,booleanValue)/If booleanValue is false, this method does not include the specified key's key

tailMap() method starts returning all keys of the TreeMap from the specified key (passed as a parameter)

booleanValue is an optional parameter. The default value is true./If booleanValue is false, this method does not include the specified key's key

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("First", 1);
        numbers.put("Second", 2);
        numbers.put("Third", 3);
        numbers.put("Fourth", 4);
        System.out.println("TreeMap: " + numbers);
        value pairs.
        // System.out.println("\nUsing tailMap() method:");
        tailMap() booleanValue using default value true + System.out.println("booleanValue using default true: "
        // numbers.tailMap("Second"));
        tailMap() booleanValue using specified value false + System.out.println("booleanValue using specified false: "
    }
}

Output Result

TreeMap: {First=1, Fourth=4, Second=2, Third=3}
numbers.tailMap("Second", false));
Using tailMap() method:2, Third=3}
booleanValue using default true: {Second=3}

booleanValue using specified false: {Third=1,k1subMap(k2,k2,bV

)1and2subMap() method returns all entries associated with k1entries.

all entries associated with keys between1and bV2is an optional boolean parameter. bV1is true by default, bV2is false by default.

if bV1if bV is false, then this method returns all entries associated with k1and2all entries associated with keys between1entries.

if bV2if both k and1and2all entries associated with keys between2entries.

For example,

import java.util.TreeMap;
class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> numbers = new TreeMap<>();
        numbers.put("First", 1);
        numbers.put("Second", 2);
        numbers.put("Third", 3);
        numbers.put("Fourth", 4);
        System.out.println("TreeMap: " + numbers);
        System.out.println("\nUse the subMap() method:")
        // tailMap() use default boolean value
        System.out.println("Use default boolean value: ") + numbers.subMap("Fourth", "Third"));
        // tailMap() specify a boolean value
        System.out.println("Specify a boolean value: ") + numbers.subMap("Fourth", false, "Third", true));
    }
}

Output Result

TreeMap: {First=1, Fourth=2, Second=2, Third=3}
Use the subMap() method:
Use default boolean value: {Fourth=4, Second=2}
Specify a boolean value: {Second=2, Third=3}

Other TreeMap methods

MethodDescription
clone()Create a copy of TreeMap
containsKey()Search for a specified key in TreeMap and return a boolean result
containsValue()Search for a specified value in TreeMap and return a boolean result
size()Return the size of TreeMap
clear()Remove all entries from TreeMap

TreeMap Comparator

In all the above examples, the TreeMap elements are naturally sorted (in ascending order). However, we can also customize the order of the keys.

To do this, we need to create our own comparator class based on the sorting method of the keys in the tree map. For example,

import java.util.TreeMap;
import java.util.Comparator;
class Main {
    public static void main(String[] args) {
        //Create a TreeMap using a custom comparator
        TreeMap<String, Integer> numbers = new TreeMap<>(new CustomComparator());
        numbers.put("First", 1);
        numbers.put("Second", 2);
        numbers.put("Third", 3);
        numbers.put("Fourth", 4);
        System.out.println("TreeMap: " + numbers);
    }
    //Create a comparator class
    public static class CustomComparator implements Comparator<String> {
        @Override
        public int compare(String number1, String number2) {
            int value =  number1.compareTo(number2);
            //Elements are sorted in reverse order
            if (value > 0) {
                return -1;
            }
            else if (value < 0) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }
}

Output Result

TreeMap: {Third=3, Second=2, Fourth=4, First=1}

In the above example, we create a TreeMap and pass the CustomComparator class as a parameter.

The CustomComparator class implements the Comparator interface.

Then override the compare() method to sort elements in reverse order.