-1

I need to create a map from primitive array of integers where key is index and value is element by current index. How can i do it using a Java Stream API?

I'm trying to do something like this but it doesn't work out for me.

        IntStream.range(0, nums.length)
                .collect(Collectors.toMap(i -> i, i -> nums[i]));
Naman
  • 27,789
  • 26
  • 218
  • 353
  • It’s must faster to look at Javadoc instead of waiting for help from strangers. – Abhijit Sarkar Jul 25 '21 at 08:54
  • 2
    Could you explain ["but it doesn't work"](https://web.archive.org/web/20180124130721/http://importblogkit.com/2015/07/does-not-work/)? – Pshemo Jul 25 '21 at 08:54

1 Answers1

2

IntStream doesn't have the collect() method you are trying to use, so you have to convert your IntStream to a Stream<Integer>:

Map<Integer,Integer> map =
    IntStream.range(0, nums.length)
             .boxed()
             .collect(Collectors.toMap(Function.identity(), i -> nums[i]));
Eran
  • 387,369
  • 54
  • 702
  • 768