TreeMap in Java

In Java, TreeMap is the implementation of SortedMap. The properties of the TreeMap class in Java are given below.

  • The underlying data structure is the Red-Black Tree.
  • Insertion order is not preserved
  • Duplicate keys are not allowed but values can be duplicated
  • If we are using the default natural sorting order then keys should be homogenous and comparable otherwise we will get ClassCastException Runtime Error.
  • If we are defining our sorting then keys are not to be homogenous and comparable.

TreeMap Null Acceptance Properties

  • For non-empty TreeMap null insertion is not allowed.
  • For empty TreeMap null key is allowed as a first entry (atmost one)

Note- The above null acceptance rule is qpplicable until Java 1.6v. From Java 1.6v onwards null is not allowed for key but we can use null as a value any number of times.

TreeMap Constructors in Java

TreeMap tree = new TreeMap(); //Default sorting order
TreeMap tree = new TreeMap(Comparator c); //Customize sorting order
TreeMap tree = new TreeMap(SortedMap m);
TreeMap tree = new TreeMap(Map m);

TreeMap Example Code

import java.util.TreeMap;

public class TreeMapExample {

    public static void main(String[] args) {

        TreeMap treeMap = new TreeMap();
        treeMap.put(1,"The");
        treeMap.put(2,"Code");
        treeMap.put(3,"Data");

        System.out.println(treeMap);
    }
}
treemap in java

In the above Java code elementes are sorted according to the default sorting order.

Let’s write another java Program and implement customized sorting order in TreeMap.

TreeMap Example Code for Customize Sorting

import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapCustomizedSortingExample {

    public static void main(String[] args) {

        TreeMap treeMap = new TreeMap(new CustomizedComparator());
        treeMap.put("b",100);
        treeMap.put("z",230);
        treeMap.put("d",688);
        treeMap.put("t",655);
        treeMap.put("a",455);
        treeMap.put("c",999);

        System.out.println(treeMap);
    }
}
class CustomizedComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        String str1 = o1.toString();
        String str2 = o2.toString();
        return str2.compareTo(str1);
    }
}
how to implement treemap in java

Similar Java Tutorials

Leave a Comment