TreeMap in Java

TreeMap (Since Java1.2):

  • Underlying data structure is Red-Black tree.
  • Insertion order is not preserved since objects will be inserted based on some sorting technique.
  • If you use your own sorting order using Comprator then the key objects need not be Homogenous and Comparable.
  • No restriction on Values. They can be heterogeneous and non-comparable.
  • Duplicate keys are not allowed but duplicate values are allowed.
  • Homogenous and Comparable: If you need default sorted order, the key objects which you are adding in a TreeMap should be Homogenous and Comparable. Otherwise we will get ClassCaseException.

Null acceptance in TreeMap:

  • NullPointerException will come, if you add elements in a non-empty TreeMap.
  • It’s possible to add null as first element in the empty TreeMap.  NullPointerException will come if you add any other element after inserting null.
  • So the thing you can add only one null element in a TreeMap and you will get NPE if you try to add either null or element after insertion of null.

Constructors in TreeMap :

1)      TreeMap tm = new TreeMap();

It creates empty TreeMap object in which the sorting order is default natural sorting order.

2)      TreeMap tm = new TreeMap (Comparator comparator)

It creates empty TreeMap object in which the sorting order is customized sorting order specified by comparator

3)      TreeMap tm = new TreeMap (Collection c)

It creates empty TreeMap object with the specified collection

4)      TreeMap tm= new TreeMap (SortedMap s)

It creates empty TreeMap object with the specified sorted map

TreeMap example using comparator.

 Output:

 

Posted in collections and tagged , .

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">