how to create TreeMap using comparator in collections in java
Previous | Home | Next |
In this example we will create a TreeMap by using the comparator interface.
For creating a TreeMap first of all we have to import the java.util package in which the java.util.TreeMap class is defined. In this example we have created a class named CollectionExample in which we have created a TreeMap and added some elements to it.
For adding the elements to a TreeMap, we use the put(Object key, Object value) method on its object.
In this example we have created a TreeSet object and used the comparator interface for controlling the ordering of the elements of the TreeSet. For using the comparator interface we have created an anonymous class and then added some elements to the object of the TreeSet by using the put(Object key, Object value) method on it.
Finally we have displayed the contents of the TreeSet.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String args[]) throws IllegalArgumentException, NullPointerException
{
try
{
/* In the code given below we have created an object of TreeMap i.e tm, and creted an anonymous
* class of the Comparator which sorts the tree set in the last element first manner
*/
TreeMap<Integer, String> tm=new TreeMap<Integer, String>(new Comparator<Integer>()
{
public int compare(Integer i, Integer j)
{
return -1;
}
});
tm.put(1, "r4r"); // adding elements to the treeSet
tm.put(2, "tutorials");
tm.put(3, "development");
tm.put(4, "shashi");
tm.put(5, "s/w engineer");
System.out.println("The contents of the TreeSet are as follows: ");
Set set=tm.entrySet(); // creating a set of the contents of the TreeSet
Iterator itr=set.iterator(); // Invoking the iterator on the set
while(itr.hasNext())
{
Map.Entry<Integer, String> map = (Map.Entry<Integer, String>)itr.next(); // using the Map.Entry interface
int key=map.getKey(); // getting the key contained in the treeSet
String value=map.getValue(); // getting the values contained in the treeSet
System.out.print("KEY := "+key); // printing the key
System.out.print(","+"VALUE := "+value); // printing the value
System.out.println();
}
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
}
catch(NullPointerException e)
{
e.printStackTrace();
}
}
}
The output of the above given example is the following one:
The contents of the TreeSet are as follows:
KEY := 5,VALUE := s/w engineer
KEY := 4,VALUE := shashi
KEY := 3,VALUE := development
KEY := 2,VALUE := tutorials
KEY := 1,VALUE := r4r
As expected we stored the elements in the reverse of the order in which the elements were put into the TreeMap as defined by our comparator.
Previous | Home | Next |