我有一个 Employee 列表(Employee 是一个类)。员工有 3 个属性
private String name
private int yearsSpentInCompany
private boolean parkingSpace
并且具有这些属性的构造函数
public Employee(String name, int yearsSpentInCompany, boolean parkingSpace) {
this.name = name;
this.yearsSpentInCompany = yearsSpentInCompany;
this.parkingSpace = parkingSpace;}
一览是这个
List<Employee> allEmployeesOfCompany = new ArrayList<Employee>();
例如,我的列表中有 10 名员工。我如何获取没有任何 parking 位的员工列表(parkingSpace = false),以及根据在公司工作的年限排序的相同列表。
我不完整的解决方案:我在公司工作多年定义了自己的比较器
import java.util.Comparator;
public class YearsComp implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
if (o1.getYearsSpentInCompany() > o2.getYearsSpentInCompany()) {
return 1;
} else {
return -1;
}
}
}
输出为
=== Employees sorted by seniority in work ===
Employee: Vlad === YearsSpentInCompany: 1 === ParkingPlace:true
Employee: Ayian === YearsSpentInCompany: 2 === ParkingPlace:true
Employee: Ion === YearsSpentInCompany: 2 === ParkingPlace:true
Employee: Victor === YearsSpentInCompany: 2 === ParkingPlace:false
Employee: Aurel === YearsSpentInCompany: 8 === ParkingPlace:false
Employee: Tudod === YearsSpentInCompany: 10 === ParkingPlace:true
Employee: Sebi === YearsSpentInCompany: 13 === ParkingPlace:true
Employee: Marcel === YearsSpentInCompany: 15 === ParkingPlace:false
Employee: Raul === YearsSpentInCompany: 16 === ParkingPlace:true
Employee: Andrei === YearsSpentInCompany: 17 === ParkingPlace:false
排序很好。 Emplyee 类在该类中实现了 Comparable 和 i Ovveride:
@Override
public int compareTo(Object o) {
if( this.parkingSpace == false)
System.out.println("No parking place: " + this.getName());
return 0;
}
输出为
No parking place: Marcel ---15 years
No parking place: Aurel ---- 8 years
No parking place: Victor ---- 2 years
No parking place: Andrei --- 17 years
这部分正确,因为我想按照在这样的公司工作的年限对没有 parking 位的员工进行排序
No parking place: Victor ---- 2 years
No parking place: Aurel ---- 8 years
No parking place: Marcel ---15 years
No parking place: Andrei --- 17 years
如何结合这两种方法?
最佳答案
使用 compareTo
来获取没有 parking 场的员工是没有意义的。 compareTo
应该用于排序(以及 TreeSet
中的唯一性测试),而不是用于过滤。
您可以使用 Java 8 Stream
轻松过滤和排序:
List<Employee> output =
allEmployeesOfCompany.stream()
.filter(emp -> !emp.parkingSpace)
.sorted(Comparator.comparingInt(Employee::getYearsSpentInCompany))
.collect(Collectors.toList());
关于java - <Employe> 的 TreeSet 列表对列表进行排序并显示列表中具有特定属性的人员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48732164/