从 int 数组创建一个 Map,其中索引作为键,值作为 java 中的数组元素

create a Map from int array with index as key and value as array element in java

这是我的整数数组

[9,3,15,20,7]

我想创建一个类似

的地图

0->9 1->3

以索引为键,数组元素为值

IntStream.range(0,postorder.length).collect(Collectors.toMap(i -> postorder[i],i->i));

我这样试过,但出现编译错误,因为找到了所需的 int 类型对象 有没有在java

中使用流创建这样的地图
IntStream.range(0, postorder.length)
         .boxed()
         .collect(Collectors.toMap(i -> i, i -> postorder[i], (a, b) -> b));

你应该boxed() IntStream

final int[] postorder = {2,5, 6, 8};
Map<Object, Object> map = IntStream
        .range(0,postorder.length)
        .boxed()
        .collect(Collectors.toMap(index -> index, index-> postorder[index]));
System.out.println(map);