【发布时间】:2021-08-13 08:19:26
【问题描述】:
我需要您的帮助来确定我现在正在处理的代码有什么问题。
这个任务的规范是过滤从一个csv文件中获取的对象列表,只得到薪水最高的前10名员工。我正在尝试这些行:
List<Employee> listOfTop10HighestPaidMaleEmployee = new ArrayList<>(employeeList);
List<Employee> filterSalary;
filterSalary = listOfTop10HighestPaidMaleEmployee
.stream()
.sorted(
Comparator.comparingDouble(Employee::getSalary)
)
.limit(10)
.collect(Collectors.toList());
当我使用 for-each 循环对其进行测试时,它会打印出 10 个值,但没有正确过滤掉薪水部分。我得到这个输出:
Employee{id='261461', name='Lucila Isai Gray Silvestre', department='Software Development Team',
gender=M, age=34, employment status=Permanent, salary=20079.75, years of service=9}
Employee{id='368487', name='Joey Quinn Uson Solivio', department='Marketing', gender=M, age=34,
employment status=Not Permanent, salary=20200.25, years of service=3}
Employee{id='353810', name='Carter Jamie Pagsisihan Lingao', department='Marketing', gender=M,
age=24, employment status=Permanent, salary=20444.25, years of service=4}
Employee{id='330680', name='Erick Colby Magan Formalouza', department='IT Services', gender=M,
age=52, employment status=Permanent, salary=20887.0, years of service=14}
Employee{id='220888', name='Jack Cornelius Parker Guinto', department='IT Services', gender=M,
age=32, employment status=Permanent, salary=20950.0, years of service=10}
Employee{id='215350', name='Eugenio Jermaine Quiblat Bonachita', department='Marketing', gender=M,
age=45, employment status=Not Permanent, salary=21263.5, years of service=2}
Employee{id='257430', name='Malaya Kaitlyn Hakamada Gonz�lez', department='IT Services', gender=F,
age=35, employment status=Not Permanent, salary=21362.0, years of service=2}
Employee{id='212292', name='Kendra Mercedes Lomondot Fernando', department='Marketing', gender=F, a
age=41, employment status=Not Permanent, salary=21371.75, years of service=3}
Employee{id='348771', name='Kristofer Israel Dura Portugal', department='Human Resource', gender=M,
age=49, employment status=Permanent, salary=21402.5, years of service=6}
Employee{id='353227', name='Maegan Jaden Mahiya Isidro', department='Human Resource', gender=F,
age=59, employment status=Not Permanent, salary=21442.25, years of service=3}
在交叉检查结果和列表后,它会打印出工资范围为 20000-21,000 的列表。在原始名单中,薪水高达30,000。关于如何过滤列表以显示工资最高的 10 名员工的列表的任何提示?任何帮助将不胜感激。提前谢谢!
【问题讨论】:
-
Comparator.comparingDouble(Employee::getSalary)将按升序排序。你需要扭转它:Comparator.comparingDouble(Employee::getSalary).reversed()或类似的东西。 -
@ernest_k 谢谢!终于找到我要找的结果了。
标签: java filter java-stream e