Saturday, 11 April 2015

Java TreeMap Example


  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.


Hierarchy of TreeMap class:
Example of TreeMap class:

package com.mnb;

import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapDemo {

public static void main(String[] args) {
TreeMap<Integer, String> tm = new TreeMap<Integer, String>();

tm.put(1, "Power");
tm.put(2, "Star");
tm.put(4, "Kalyan");
tm.put(3, "Pawan");
System.out.println("Automatically sorted by natural order of Keys from TreeMap:");
for (Map.Entry<Integer,String> me : tm.entrySet()) {
System.out.println(me.getKey() + " : " + me.getValue());
}

System.out.println("To get a reverse order view of Mapping from TreeMap:");

NavigableMap<Integer,String> reverseTreeMap = tm.descendingMap();

Set<Integer> keySet = reverseTreeMap.keySet();
for (Integer key : keySet) {
System.out.println(key + " : " + reverseTreeMap.get(key));
}

// To get first and last entry from TreeMap in Java

System.out.println("First Entry: " + tm.firstEntry());
System.out.println("Last Entry: " + tm.lastEntry());

// To get first and last key from TreeMap in Java

System.out.println("First Key: " + tm.firstKey());
System.out.println("Last Key: " + tm.lastKey());

// Creating subMap from TreeMap in Java
SortedMap<Integer,String> subMap = tm.subMap(3, 5);
System.out.println("SubMap: " + subMap);

// Creating headMap and tailMap from TreeMap in Java

SortedMap<Integer,String> headTreeMap = tm.headMap(3);
SortedMap<Integer,String> tailTreeMap = tm.tailMap(3);
System.out.println("Head Map: " + headTreeMap);
System.out.println("Tail Map: " + tailTreeMap);

}
}

Output:


Automatically sorted by natural order of Keys from TreeMap:
1 : Power
2 : Star
3 : Pawan
4 : Kalyan
To get a reverse order view of Mapping from TreeMap:
4 : Kalyan
3 : Pawan
2 : Star
1 : Power
First Entry: 1=Power
Last Entry: 4=Kalyan
First Key: 1
Last Key: 4
SubMap: {3=Pawan, 4=Kalyan}
Head Map: {1=Power, 2=Star}
Tail Map: {3=Pawan, 4=Kalyan}

No comments:

Post a Comment