TreeMap in java with examples
TreeMap class implements Map similar to HashMap.
Some important points about TreeMap:
- TreeMap implements Map interface and extends HashMap class.
- TreeMap is implemented using Red black tree based NavigableMap.
- TreeMap is ordered collection and store its elements in natural ordering of keys.
- Key which you would like to put in TreeMap must implement Comaparable interface or you can use Comparator for custom sorting
Example:
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 Country.java 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.
Example:
Create Country.java as below. It should implement Comparable interface
Create TreeMapCompMain.java as below:
When you run program, you will get below output:
1
2
3
4
5
6
7
|
Sorting HashMap by passing it to TreeMap constructor
France----Paris
India----Delhi
Japan----Tokyo
Russia----Moscow
|