TreeMap in java with examples


TreeMap class implements Map similar to HashMap.

Some important points about TreeMap:

  1. TreeMap implements Map interface and extends HashMap class.
  2. TreeMap is implemented using Red black tree based NavigableMap.
  3. TreeMap is ordered collection and store its elements in natural ordering of keys.
  4. Key which you would like to put in TreeMap must implement Comaparable interface or you can use Comparator for custom sorting

When you run above program, you will get following output:

As you can see, it is sorted in ascending order of Key(Country)

What if you want custom sorting rather than natural ordering:

If you want custom sorting , then you can using below TreeMap constructor. You can define your own comparator.

Example: Create as below

Create TreeMapCompMain as below:

When you run above program, you will get below output:

You can pass HashMap to constructor of TreeMap to sort it on Key

By passing HashMap to constructor of TreeMap, you can sort TreeMap.

Create as below. It should implement Comparable interface

Create as below:

When you run program, you will get below output:

Related posts

Add Comment