1

I have already created a comparator for the priority queue.

class CompareBySalary implements Comparator<Employee>{
    @Override
    public int compare(Employee e1,Employee e2){
        return e1.salary<e2.salary ? -1 : e1.salary>e2.salary ? 1 : 0;
        
    }
}

class Employee{
    String name;
    float salary;
    Employee(String name,float salary){
        this.name=name;
        this.salary=salary;
    }
}

 public class TryCode{
     
     public static void main(String args[])
     {
        
         Employee e1=new Employee("C",10000);
         Employee e2=new Employee("A",5000.45f);
         Employee e3=new Employee("D",15000);
         Employee e4=new Employee("B",5000.67f);
         Queue<Employee> q=new PriorityQueue(new CompareBySalary());
         q.offer(e1);
         q.offer(e2);
         q.offer(e3);
         q.offer(e4);
         for(Employee e:q)
             System.out.println(e.name);
            
     }
     
     
 }

This gives the output:A B D C Why is it not sorting correctly? Is it something I am missing? P.S. I have already tried with Float.compare() it gives the same output.

1 Answers1

0
  1. Change your domain model as follows:

     class Employee implements Comparable<Employee> {
         private String name;
         private float salary;
    
         Employee(String name, float salary) {
             this.name = name;
             this.salary = salary;
         }
    
         public String getName() {
             return name;
         }
    
         public float getSalary() {
             return salary;
         }
    
         @Override
         public int compareTo(Employee o) {
             if (o1.getSalary()>o2.getSalary()) {
                 return 1;
             } else if (o1.getSalary()<o2.getSalary()) {
                 return -1;
             } else {
                 return 0;
             }
         }
     }
    
  2. Remove CompareBySalary (you won't need it)

  3. Create your PriorityQueue like this:

    PriorityQueue<Employee> q = new PriorityQueue<>(Comparator.comparingDouble(Employee::getSalary));
    
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
  • Thank You! I was just practicing comparators and so I just wrote it quickly in its primitive form.Just wanted to check the working.I appreciate your comment.It has been solved now that I got to know the problem was in System.out.println() as it internally uses toString() which doesn't display in the sorted order of the priority queue.Using poll displays it in sorted order. – Royston Furtado Aug 09 '20 at 19:34
  • 1
    You have to `.poll()`, yes, otherwise, ordinary iteration just ordinarily takes the elements. Also, note, that you can implement this in several other ways.. for examples, implement comparator logic in the lambda argument.. or implement anonymous inner class.. and etc. – Giorgi Tsiklauri Aug 09 '20 at 19:39