javacomparatorpriority-queuefloating-point-comparison

I have a PriorityQueue of Objects and I need to sort it based on float values.How do I create a comparator for it?


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.


Solution

    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));