如何用Java Stream将Driver列表转换为<Student.id, Driver.id>的HashMap?
使用Java Stream构建以Student.id为键、Driver.id为值的Map
要实现将Driver列表转换为键为Student.id、值为对应Driver.id的Map,可以通过Java Stream的flatMap和Collectors.toMap组合完成,同时需要考虑同一个学生可能属于多个司机的冲突场景。
代码实现
import java.util.AbstractMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; // 假设已有List<Driver> drivers实例 List<Driver> drivers = ...; Map<String, String> studentIdToDriverIdMap = drivers.stream() // 将每个Driver拆分为多个(Student.id, Driver.id)的键值对 .flatMap(driver -> driver.getStudents().stream() .map(student -> new AbstractMap.SimpleEntry<>(student.getId(), driver.getId()))) // 收集为Map,处理重复Student.id的情况 .collect(Collectors.toMap( Map.Entry::getKey, // 提取Student.id作为Map的键 Map.Entry::getValue, // 提取Driver.id作为Map的值 (existing, newVal) -> existing // 重复键时保留第一个关联的Driver.id,可替换为newVal覆盖 ));
关键步骤说明
- flatMap展开:通过
flatMap将每个Driver对象拆解为多个键值对,每个学生对应其所属的司机ID,实现一对多的展开。 - 冲突处理:
Collectors.toMap的第三个参数用于解决同一个学生ID对应多个司机ID的冲突。示例中保留第一个出现的司机ID,若需要覆盖为最新的,可将函数改为(existing, newVal) -> newVal。 - 无冲突场景:如果能确保每个学生仅属于一个司机,可以省略第三个参数,但此时若出现重复键会抛出
IllegalStateException。
内容的提问来源于stack exchange,提问作者hnadiger
相关产品推荐
相关产品推荐

