Java中如何通过Stream API将数组转换为HashMap
问题原因&修复方案
你写的代码存在两处错误:
- 下标流生成逻辑错误:
IntStream.of(a,b)是生成仅包含a、b两个元素的整数流,而非0到数组末尾的连续下标。你需要用IntStream.range(0, headerDisplayName.length)生成左闭右开的连续整数序列,刚好覆盖所有数组的合法下标。 - 原始类型流无法直接收集:
IntStream是Java为基础类型int设计的专用流,没有泛型信息,无法直接适配Collectors.toMap的入参要求,需要先调用.boxed()将int装箱为Integer类型,转换为泛型流Stream<Integer>后再执行收集。
正确实现代码
final String[] headerDisplayName = getHeaderDisplayName(harmonizationComponentDataFixRequest); Map<Integer, String> headerIndexMap = IntStream.range(0, headerDisplayName.length) .boxed() .collect(Collectors.toMap( Function.identity(), index -> headerDisplayName[index] ));
补充说明
由于下标天然唯一,不需要处理Collectors.toMap常见的键冲突问题,代码可以直接运行。
内容的提问来源于stack exchange,提问作者Hard Worker
相关产品推荐
相关产品推荐

