What is TreeMap in Java with example?

 

What is TreeMap in Java with example?

What is TreeMap in Java with example?

What is TreeMap in Java with example?
  • The underlying data-structure is Red-black-Tree.
  • Insertion order is not preserved and it is based on some sorting order of keys.
  • Duplicate key is not allowed but values can be duplicated.
  • If we are depending on default natural sorting order then keys should be heterogeneous and comparable. Otherwise, we will get Runtime exception saying ClassCastException.
  • If we are defining our own sorting by comparator then keys need not be homogeneous and comparable. We can take heterogeneous, non-comparable objects also.
  • Whether we are depending on default natural sorting order or customized sorting order there are no-restrictions for values. We can take heterogeneous, non-comparable objects also.

Null Acceptance

  • For non-empty TreeMap if we are trying to insert an entry with a null key then we will get RuntimeException saying NullPointerException.
  • For empty TreeMap as the first entry with a Null key is allowed but after inserting that entry if we are trying to insert any other entry then we will get RuntimeException saying NullPointerException.
  • Note:- the above acceptance rule applicable until 1.6 only.  1.7 version onward null is not allowed for Key.
  • But for values we can use Null any number of times there is no restriction whether it is 1.6v or 1.7v.

Constructors

1 TreeMap m=new TreeHashMap() Creates an empty TreeMap object for default natural sorting
2 TreeMap m=new TreeMap(Comparator c) Creates an empty TreeMap object for customized sorting order
3 TreeMap m=new TreeMap(SortedMap s) Creates an empty TreeMap object with sorting order as given
4 TreeMap m=new TreeMap(Map m) create a TreeMap with equivalent given Map object.
//Demo program for cutomized sorting
package com.java4us;

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

class Test {
    public static void main(String[] args) throws InterruptedException {
        TreeMap m = new TreeMap(new myComparator());
        m.put(101, "Welcome");
        m.put(102, "To");
        m.put(109, "Java4US");
        m.put(106, "Dot");
        m.put(105, "Com");
        System.out.println(m);  //{109=Java4US, 106=Dot, 105=Com, 102=To, 101=Welcome}
    }
}

class myComparator implements Comparator {

    public int compare(Object obj1, Object obj2) {
        Integer i1 = (Integer) obj1;
        Integer i2 = (Integer) obj2;
        if (i1 > i2) {
            return -1;
        } else if (i1 < i2) {
            return +1;
        } else
            return 0;
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*