Java TreeMap

Java TreeMap


Java TreeMap implements the Java Map interface and the key/value pairs in a TreeMap will be sorted in an ascending key order. In the following example, we create a TreeMap and adding some elements to it.


import java.util.TreeMap;

public class AddingElementsTreeMap {
    public static void main(String[] args) {
        TreeMap<Integer,String> cities = new TreeMap<>();
        
        cities.put(1, "Helsingborg");
        cities.put(5, "Stockholm");
        cities.put(3, "Göteborg");
        cities.put(2, "Malmö");
        cities.put(4, "Uppsala");

        System.out.println("Cities : " + cities);
    }
}


Output:


$ javac AddingElementsTreeMap.java
$ java AddingElementsTreeMap
Cities : {1=Helsingborg, 2=Malmö, 3=Göteborg, 4=Uppsala, 5=Stockholm}


We use put() method to add elements to a TreeMap.
In the following example, we will use few TreeMap methods to check if its empty, check the size of the TreeMap and remove elements.


import java.util.TreeMap;

public class TreeMapMethods {
    public static void main(String[] args) {
        TreeMap<Integer,String> cities = new TreeMap<>();
        
        cities.put(1, "Helsingborg");
        cities.put(5, "Stockholm");
        cities.put(3, "Göteborg");
        cities.put(2, "Malmö");
        cities.put(4, "Uppsala");
        cities.put(10, "Candy");

        System.out.println("Cities Before Remove: " + cities);

        // We use remove() method to remove elements
        cities.remove(10);

        System.out.println("Cities After Remove: " + cities);

        // check if TreeMap contains the key 10
        System.out.println("City with id 10 exists: " + cities.containsKey(10));

        System.out.println("First entry in cities map: " + cities.firstEntry());
        System.out.println("Last entry in cities map: " + cities.lastEntry());

        // size() method is used to find the size of the TreeMap
        System.out.println("Size: " + cities.size());

        // check if cities map is empty
        System.out.println("Citites map is empty: " + cities.isEmpty());

        // get() method will retrieve the value mapped by the specified key
        System.out.println("City " + cities.get(1));

        // clear() method will remove all the key-value pairs from the map
        cities.clear();
        System.out.println("City " + cities);

        System.out.println("Citites map is empty: " + cities.isEmpty());
    }
}


containsKey() method will return true if the specified key is present in the map.
remove() method will remove the entry for the specified key if is present.
firstEntry() will return the first element in the map.
lastEntry() will return the last element in the map.
isEmpty() will return true if the map is empty.
size() method will return the number of entries in the map.
get() method will retrieve the value mapped by the specified key.
clear() method will remove all the key-value pairs from the map.

Output:


$ javac TreeMapMethods.java
$ java TreeMapMethods
Cities Before Remove: {1=Helsingborg, 2=Malmö, 3=Göteborg, 4=Uppsala, 5=Stockholm, 10=Candy}
Cities After Remove: {1=Helsingborg, 2=Malmö, 3=Göteborg, 4=Uppsala, 5=Stockholm}
City with id 10 exists: false
First entry in cities map: 1=Helsingborg
Last entry in cities map: 5=Stockholm
Size: 5
Citites map is empty: false


The following example shows how to iterate over a TreeMap using for-each loop.


import java.util.TreeMap;
import java.util.Map;

public class IterateTreeMapUsingSimpleForLoop {
    public static void main(String[] args) {
        TreeMap<Integer,String> cities = new TreeMap<>();
        
        cities.put(1, "Helsingborg");
        cities.put(5, "Stockholm");
        cities.put(3, "Göteborg");
        cities.put(2, "Malmö");
        cities.put(4, "Uppsala");

        for (Map.Entry city : cities.entrySet()) {
            System.out.println("id: " + city.getKey() + " " + "city: " + city.getValue());
        }
    }
}


Output:


$ javac IterateTreeMapUsingSimpleForLoop.java
$ java IterateTreeMapUsingSimpleForLoop
id: 1 city: Helsingborg
id: 2 city: Malmö
id: 3 city: Göteborg
id: 4 city: Uppsala
id: 5 city: Stockholm


The following example will iterate over a TreeMap using Iterator.


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

public class IterateTreeMapUsingIteratorExample {
    public static void main(String[] args) {
        TreeMap<Integer,String> cities = new TreeMap<>();
        
        cities.put(1, "Helsingborg");
        cities.put(5, "Stockholm");
        cities.put(3, "Göteborg");
        cities.put(2, "Malmö");
        cities.put(4, "Uppsala");
        
        Set set = cities.entrySet();

        Iterator cityIterator = set.iterator();

        while(cityIterator.hasNext()) {
            Map.Entry key = (Map.Entry) cityIterator.next();
            System.out.println("Key is: " + key.getKey() + " the value is: " + key.getValue() );
        }
    }
}


Output:


$ javac IterateTreeMapUsingIteratorExample.java
$ java IterateTreeMapUsingIteratorExample
Key is: 1 the value is: Helsingborg
Key is: 2 the value is: Malmö
Key is: 3 the value is: Göteborg
Key is: 4 the value is: Uppsala
Key is: 5 the value is: Stockholm


The following example shows how to create TreeMap with a custom comparator that orders the entries in descending order.


import java.util.TreeMap;
import java.util.Collections;

public class TreeMapReverseOrder {
    public static void main(String[] args) {
        TreeMap<Integer,String> cities = new TreeMap<>(Collections.reverseOrder());
        
        cities.put(1, "Helsingborg");
        cities.put(5, "Stockholm");
        cities.put(3, "Göteborg");
        cities.put(2, "Malmö");
        cities.put(4, "Uppsala");

        System.out.println("Cities : " + cities);   
    }
}


Output:


$ javac TreeMapReverseOrder.java
$ java TreeMapReverseOrder
Cities : {5=Stockholm, 4=Uppsala, 3=Göteborg, 2=Malmö, 1=Helsingborg}


Share this: