如何使用StreamAPI在Java中将数组转换为HashMap
我试图做一些非常简单的事情,但编译失败,我不明白是谁
我有一个标题列表,我需要将其转换
Map<Index, String>为键(索引)的含义,值是标题名称
我知道如何为每个人制作它,但我想将它放在Collectors.to地图中,任何帮助将不胜感激
final String[] headerDisplayName = getHeaderDisplayName(harmonizationComponentDataFixRequest);
IntStream.of(0, headerDisplayName.length).collect(Collectors.toMap(Function.identity(), index-> headerDisplayName[index]));
回答
您可以将rangemethod 与 的boxed方法结合使用IntStream。
(当您使用of示例中的方法时,此流中只有 0 和数组的大小。此外,这会导致ArrayIndexOutOfBoundsException)
一个可能的解决方案如下所示(range包括方法的第一个参数,排除第二个参数)
Map<Integer, String> map = IntStream.range(0, headerDisplayName.length)
.boxed()
.collect(Collectors.toMap(
Function.identity(),
i -> headerDisplayName[i])
);