Set<Employee> employeeSet =
如何从Set中选择最老的Employee(它有一个属性'int age')
答案 0 :(得分:1)
您可以使用Stream API
Optional<Employee> employee = employeeSet.stream()
.max(Comparator.comparing(e -> e.age));
employee.get()
将返回Employee,除非该集合为空。
答案 1 :(得分:0)
这可能不是性能的最佳解决方案,但您可以使用增强的for循环遍历每个元素:
Employee oldest = employeeSet.get(0); // Initialize with the first index
for (Employee emp : employeeSet) {
if (emp.age > oldest.age) {
oldest = emp;
}
}
答案 2 :(得分:0)
我认为Java 8中的Stream接口可以提供帮助
final Comparator<Employee> comp = Comparator.comparingInt(Employee::getAge);
Employee oldest = employeeList.stream()
.max(comp)
.get();
详细了解此https://stevewall123.wordpress.com/2014/08/31/java-8-streams-max-and-streams-min-example/
答案 3 :(得分:0)
您可以遍历该集合。
int maxAge = 0; //
for(Employee emp: employeeSet){
if(emp.getAge() > maxAge)
maxAge = employee.getAge()
}
maxAge变量将在forEach循环结束后具有最高年龄
答案 4 :(得分:0)
您可以为查找最早的员工定义第一个年龄
int baseAge = 50;
现在您需要将所有员工年龄与此年龄进行比较
Public Set findOldest()
{
int baseAge =50;
Set < Employee > oldest = new HashSet< Employee >();
Set<Employee> employee = // your set of employees
for ( Employee emp : employee )
{
If(emp.empAge > baseAge)
oldest.add(emp);
}
return oldest;
}