Friday, 27 February 2015

Java : Collection Framework : TreeMap (Comparator)


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=pPIQIlLPVOo&list=UUhwKlOVR041tngjerWxVccw

DescendingEmployeeIdComparator.java
import java.util.Comparator;

public class DescendingEmployeeIdComparator implements Comparator<Integer>
{

    /*
     * This method used to arrange the employeeId's in descending order.
     */
    @Override
    public int compare( Integer empId1, Integer empId2 )
    {

        if( empId1 < empId2 )
        {

            return 1;
        }
        else
        {
            return -1;
        }
    }

}
TreeMapExample.java
import java.util.Comparator;
import java.util.TreeMap;

/*
 * Example of comparator() method.
 */
public class TreeMapExample
{
    public static void main( String[] args )
    {

        DescendingEmployeeIdComparator descendingEmployeeIdComparator 
                                              = new DescendingEmployeeIdComparator();

        TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(
                descendingEmployeeIdComparator);
        /*
         * Key is EmployeeId - Value is EmployeeName
         */

        treeMap.put(20, "Balu");
        treeMap.put(10, "Ajay");
        treeMap.put(40, "Carol");
        treeMap.put(30, "Dave");

        System.out.println("treeMap : " + treeMap + "\n");
        
        Comparator<?> comparator = treeMap.comparator();
        
        System.out.println("Comparator name : "+comparator.getClass().getName());

    }
}
Output
treeMap : {40=Carol, 30=Dave, 20=Balu, 10=Ajay}

Comparator name : DescendingEmployeeIdComparator
To Download DisplayAllHeadersApp Project Click the below link
https://sites.google.com/site/javaee4321/java-collections/TreeMapDemoComparator.zip?attredirects=0&d=1

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge