Search code examples
javadictionaryjava-streamintstream

Convert array to a Map of array index to value


What's wrong with this code?

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

I'm hoping to produce a Map with these values:

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

But the error is

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


Solution

  • You need to box the ints to Integers:

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