将数组转换为数组索引到值的映射

Convert array to a Map of array index to value

这段代码有什么问题?

int[] nums = new int[] {8, 3, 4};
Map<Integer,Integer> val2Idx = 
    IntStream.range(0, nums.length)
        .collect(Collectors.toMap(idx -> idx, idx -> nums[idx]));

我希望生成具有这些值的 Map

{0=8, 1=3, 2=4}

但错误是

method collect in interface IntStream cannot be applied to given types;

您需要将 int 装箱到 Integer

Map<Integer,Integer> val2Idx =
    IntStream.range(0, nums.length)
             .boxed() // Here!
             .collect(Collectors.toMap(idx -> idx, idx -> nums[idx]));

IntStream#collect requires three arguments; if you want to use the 2-argument version, you must use IntStream#boxed 将其转换为 Stream<Integer>.

int[] nums = new int[] {8, 3, 4};
Map<Integer,Integer> val2Idx = 
    IntStream.range(0, nums.length).boxed()
        .collect(Collectors.toMap(idx -> idx, idx -> nums[idx]));
System.out.println(val2Idx);

这个错误是因为 idx 它是一个对象而不是一个 int