As I'mtrying to figure out how to use the Comparator
correctly , I am trying to sort my Employee
s 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With