Convert array to a Map of array index to value

743 Views Asked by At

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;

3

There are 3 best solutions below

2
Mureinik On BEST ANSWER

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]));
0
Unmitigated On

IntStream#collect requires three arguments; if you want to use the 2-argument version, you must use IntStream#boxed to convert it to a 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);
0
Andre Moraes On

This erros it's because of the idx the it's a object and not a int