Java 8 如何使用流将一维整数数组转换为映射

Java 8 如何使用流将一维整数数组转换为映射,java-8,java-stream,collectors,Java 8,Java Stream,Collectors,我有一个整数数组,我想把它转换成一个映射。我试过使用下面的代码 但是当我尝试使用下面的格式使用Collectors.toMap()时,它不允许映射数组 代码1:它正在工作 int arr1[] = {-5, 15, 25, 71, 63}; Map<Integer, Integer> hm = new HashMap<Integer, Integer>(); IntStream.range(0, arr1.length).forEach(i -> hm.put(i,

我有一个整数数组,我想把它转换成一个映射。我试过使用下面的代码

但是当我尝试使用下面的格式使用
Collectors.toMap()
时,它不允许映射数组

代码1:它正在工作

int arr1[] = {-5, 15, 25, 71, 63};
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
IntStream.range(0, arr1.length).forEach(i -> hm.put(i, arr1[i]));
System.out.println(hm);     
intarr1[]={-5,15,25,71,63};
Map hm=新的HashMap();
IntStream.range(0,arr1.length).forEach(i->hm.put(i,arr1[i]);
系统输出打印项次(hm);
代码2:它不工作

Map<Integer, Integer> hm1=IntStream.range(0, arr1.length).collect(Collectors.toMap(i->i,i->arr1[i]));
Map hm1=IntStream.range(0,arr1.length).collect(Collectors.toMap(i->i,i->arr1[i]);

任何人都可以解释如何使用
收集器.toMap()
函数将数组转换为map吗?

我认为这里的问题是
IntStream
正在生成一个原始int流。在流到达收集器之前尝试装箱:

hm = IntStream.range(0, arr1.length).boxed().collect(Collectors.toMap(i->i,i->arr1[i]));
for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {
    System.out.println("(" + entry.getKey() + ", " + entry.getValue() + ")");
}

(0, -5)
(1, 15)
(2, 25)
(3, 71)
(4, 63)
hm=IntStream.range(0,arr1.length).boxed().collect(Collectors.toMap(i->i,i->arr1[i]);
对于(Map.Entry:hm.entrySet()){
System.out.println(“(“+entry.getKey()+”,“+entry.getValue()+”);
}
(0, -5)
(1, 15)
(2, 25)
(3, 71)
(4, 63)

您需要将
IntStream
框起来,因为它流化原始整数,这会导致编译错误。像这样尝试
boxed()

Map<Integer, Integer> result = IntStream.range(0, arr1.length).boxed().collect(Collectors.toMap(i -> i, i -> arr1[i]));
Map result=IntStream.range(0,arr1.length).boxed().collect(Collectors.toMap(i->i,i->arr1[i]);