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
  • 1 comment:

    1. I believe all of your examples of custom Comparator for data types are broken, because you never return 0 to mean objects are equal things will disappear in there and appear to not be in there when searched for! Additionally, every Comparator should return 0 whenever .equals() would to avoid elements seeming to disappear.

      See this code (sorry, top-level name stayed same as last example, but everything is TreeSet now). Other things are good but the Comparator is very flawed!
      package badHashSet;

      import java.util.TreeSet;
      import java.util.Objects;
      import java.util.Comparator;

      class Employee {
      private String name;
      private int age;
      private int salary;

      public Employee(String name, int age, int salary)
      {
      super();
      this.setName(name);
      this.setAge(age);
      this.setSalary(salary);
      }

      @Override
      public int hashCode() {
      return Objects.hash(age, name, salary);
      }

      @Override
      public boolean equals(Object obj) {
      if (this == obj)
      return true;
      if (!(obj instanceof Employee))
      return false;
      Employee other = (Employee) obj;
      return age == other.age && Objects.equals(name, other.name) && salary == other.salary;
      }

      public String getName() {
      return name;
      }

      public void setName(String name) {
      this.name = name;
      }

      public int getAge() {
      return age;
      }

      public void setAge(int age) {
      this.age = age;
      }

      public int getSalary() {
      return salary;
      }

      public void setSalary(int salary) {
      this.salary = salary;
      }

      @Override
      public String toString()
      {
      return "Employee [name= " + name + ", age= " + age + ", salary= " + salary+"]";
      }
      }

      class BadComparator implements Comparator
      {
      public int compare(Employee emp1, Employee emp2)
      {
      if (emp1.getAge()< emp2.getAge() ) return -1;
      else return 1;
      }
      }
      public class BadHashSet {

      public static void main(String[] args) {
      TreeSet employees = new TreeSet<>(new BadComparator());
      Employee batman = new Employee("Batman", 80, 100_000);
      Employee superman = new Employee("Superman", 83, 250_000);
      Employee wonderWoman = new Employee("WonderWoman", 74, 160_000);
      // note: I prefer to store year of birth which does not change rather
      // than age which changes every year, but it helps show this problem!
      employees.add( batman );
      employees.add( superman );
      employees.add( wonderWoman );

      for( var emp : employees)
      {
      System.out.println(emp);
      }


      System.out.println("Who is in there now?");
      System.out.println("Is batman?" + employees.contains(batman));
      System.out.println("Is superman?" + employees.contains(superman));
      System.out.println("Is wonder woman?" + employees.contains(wonderWoman));

      System.out.println("They are all gone, we'd better re-add them!!");
      employees.add(batman);
      employees.add(superman);
      employees.add(wonderWoman);

      System.out.println("That was close!! Let's see if it worked?");
      for( var emp : employees)
      {
      System.out.println(emp);
      }

      System.out.println("Who is in there now?");
      System.out.println("Is batman?" + employees.contains(batman));
      System.out.println("Is superman?" + employees.contains(superman));
      System.out.println("Is wonder woman?" + employees.contains(wonderWoman));

      System.out.println("Where did they all go? The BadComparator lost them!");

      }



      }

      ReplyDelete