如何使用Java 8 Stream API获取Map中薪资第二高的员工姓名?
获取Map中薪资第二高的员工姓名(Java 8 Stream实现)
核心思路
要解决这个问题,我们需要结合Java 8 Stream的排序、过滤、跳过等操作,同时处理薪资重复、集合元素不足等边界场景:
- 将Map的键值对转换为Stream流
- 按薪资降序排序
- 跳过所有最高薪资的条目
- 提取剩余条目中的员工姓名
代码实现
方式一:先提取去重薪资档位,再匹配员工
这种方式适合需要明确区分薪资层级的场景(比如多个员工拿最高薪时,第二高是下一个薪资档位的员工):
import java.util.Map; import java.util.Optional; public class EmployeeSalaryHandler { public static Optional<String> getSecondHighestPaidEmployee(Map<String, Long> employeeSalaries) { // 先获取去重后的薪资列表,按降序排列并跳过最高档 return employeeSalaries.values() .stream() .distinct() .sorted((s1, s2) -> Long.compare(s2, s1)) .skip(1) .findFirst() // 根据第二高薪资匹配对应的员工姓名 .flatMap(targetSalary -> employeeSalaries.entrySet() .stream() .filter(entry -> entry.getValue().equals(targetSalary)) .map(Map.Entry::getKey) .findFirst()); } }
方式二:直接跳过最高薪资条目
这种方式更简洁,直接跳过所有与最高薪资相同的条目,取第一个剩余的员工:
import java.util.Map; import java.util.Optional; public class EmployeeSalaryHandler { public static Optional<String> getSecondHighestPaidEmployee(Map<String, Long> employeeSalaries) { // 先获取当前最高薪资 Optional<Long> maxSalary = employeeSalaries.values().stream().max(Long::compare); return maxSalary.flatMap(salary -> employeeSalaries.entrySet() .stream() .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // 跳过所有等于最高薪资的条目 .skipWhile(entry -> entry.getValue().equals(salary)) .map(Map.Entry::getKey) .findFirst() ); } }
关键注意点
- 使用
Optional作为返回类型:避免空指针异常,同时明确提示调用者可能没有有效结果(比如集合元素不足2个、所有薪资相同) - 重复薪资处理:两种方式都能正确应对多个员工拿最高薪的情况,确保返回的是下一档薪资的员工
- 扩展场景:如果需要获取所有薪资第二高的员工,只需把
findFirst()替换为collect(Collectors.toList())
内容的提问来源于stack exchange,提问作者Curious Coder
相关产品推荐
相关产品推荐

