试图通过HashSet的构造函数传递Comparator

myd*_*ler 3 java lambda comparator

由于Comparator我正在试图弄清楚如何正确使用,我正试图将我的Employees 排序HashSet.所以我这样做了:

Set<Employee> EmployeeSet = new HashSet<Employee>((a,b)->a.getAge()-b.getAge());
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我试图按年龄对它进行排序,但是当我使用这个lambda表达式时,它会产生编译错误,所以我想这里的东西不对.

这是我的Employee班级:

class Employee {    
    String name;
    int age;
    // constructor, getters and setters
}
Run Code Online (Sandbox Code Playgroud)

编辑:

使用PriorityQueue,它可以完美地运行:

Queue<Employee> list = new PriorityQueue<Employee>((a,b)->a.getAge()-b.getAge());
Run Code Online (Sandbox Code Playgroud)

这是为什么?

Nam*_*man 5

您可以使用a TreeSet确保Set基于的订购Comparator

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

HashSet另一方面,不接受Comparator其构造函数初始化内.

编辑:

Queue<Employee> list = new PriorityQueue<>(Comparator.comparingInt(Employee::getAge));
Run Code Online (Sandbox Code Playgroud)

工作正常,因为,PriorityQueue再次是一个有序的集合,接受Comparator其中一个构造函数.