Wednesday 14 January 2015

Java : Collection Framework : TreeSet (Comparator method)


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

AscendingNameComparator.java
import java.util.Comparator;

public class AscendingNameComparator implements Comparator<String>
{

    /*
     * This method used to arrange the names in ascending order.
     */
    @Override
    public int compare( String name1, String name2 )
    {

        return name1.compareTo(name2);
    }

}
TreeSetExample.java
import java.util.Comparator;
import java.util.TreeSet;

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

        AscendingNameComparator ascendingNameComparator = new AscendingNameComparator();
        
        TreeSet<String> treeSet = new TreeSet<String>(ascendingNameComparator);

        treeSet.add("Balu");
        treeSet.add("Ajay");
        treeSet.add("David");
        treeSet.add("Charles");

        /*
         * Returns the comparator used to order the elements in this set, or
         * null if this set uses the natural ordering of its elements.
         */

        Comparator<?> comparator = treeSet.comparator();

        System.out.println("comparator used : "
                + comparator.getClass().getName());

    }
}
Output
comparator used : AscendingNameComparator
To Download TreeSetDemoComparatorMethod Project Click the below link
https://sites.google.com/site/javaee4321/java-collections/TreeSetDemoComparatorMethod.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