Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to pass a Comparator through the constructor of a HashSet

As I'mtrying to figure out how to use the Comparator correctly , I am trying to sort my Employees in a HashSet. So I did this:

Set<Employee> EmployeeSet = new HashSet<Employee>((a,b)->a.getAge()-b.getAge());

As you can see, I tried to sorted it by age, but when I am using this lambda expression, it produces a compilation error , so I guess something isn't right here.

This is my Employee class:

class Employee {    
    String name;
    int age;
    // constructor, getters and setters
}

Edit:

With a PriorityQueue it works perfectly:

Queue<Employee> list = new PriorityQueue<Employee>((a,b)->a.getAge()-b.getAge());

Why is that?

like image 353
mydDeveler Avatar asked Dec 24 '22 00:12

mydDeveler


1 Answers

You can use a TreeSet which ensures an ordered Set based on the Comparator

Set<Employee> employeeSet = new TreeSet<>(Comparator.comparingInt(Employee::getAge));
// (a, b) -> a.getAge() - b.getAge() >>> Comparator.comparingInt(Employee::getAge

The HashSet on the other hand doesn't accept a Comparator within its constructor for initialization.

Edit:

Queue<Employee> list = new PriorityQueue<>(Comparator.comparingInt(Employee::getAge));

works fine since, PriorityQueue is again an ordered collection which accepts a Comparator in one of its constructors.

like image 75
Naman Avatar answered May 08 '23 10:05

Naman