-2

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;

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
kane
  • 5,465
  • 6
  • 44
  • 72

3 Answers3

3

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]));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Just to add some rationale: main problem is that `IntStream` doesn't *have* method like `collect(Collector)` but **only** `collect​(Supplier supplier, ObjIntConsumer accumulator, BiConsumer combiner)` so `Collectors.toMap` isn't treated as proper argument so it doesn't even have a chance to infer that `idx` is `int`. Simple fix is to use `Stream` version which has that method and can be easily created as shown in the answer. – Pshemo Dec 12 '20 at 20:42
  • Alternative fix would be providing all 3 required parameters like `.collect( HashMap::new, (map, index) -> map.put(index, nums[index]), (mainMap, otherMap) -> mainMap.putAll(otherMap) );` – Pshemo Dec 12 '20 at 20:48
1

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);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

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

Andre Moraes
  • 379
  • 1
  • 8