Error collecting IntStream to display

Following code

String[] values = ...
.... 
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < values.length; i++) {
    map.put("X" + i, values[i]);
}

Converts IntelliJ to:

Map<String, Object> map = IntStream.range(0, values.length)
        .collect(Collectors.toMap(
                i -> "X" + i,
                i -> values[i],
                (a, b) -> b));

which can be reduced to

Map<String, Object> map = IntStream.range(0, values.length)
            .collect(Collectors.toMap(
                    i -> "X" + i,
                    i -> values[i]));

2 stream versions do not compile.

IntelliJ, indicates that there is a problem with i in the [i] values:

Incompatible types.
      Requires: int
      Found: java.lang.Object

The compiler complains:

Error: (35, 17) java: the method collects in the java.util.stream.IntStream interface cannot be applied to the specified types; required: java.util.function.Supplier, java.util.function.ObjIntConsumer, java.util.function.BiConsumer
  found: java.util.stream.Collector>
  Reason: cannot call a variable of type (s) R
    (actual and formal argument lists vary in length)

Can someone explain why?

+6
1

, intelliJ, .

System.out.print(map);

, "", .


IntStream#collect , collect , ,

Collectors.toMap(i -> "X" + i, i -> values[i])

Collector.


, ,

  • forEach

    Map<String, Object> map;
    IntStream.range(0, values.length).forEach(i -> map.put("X" + i, values[i]));
    
  • boxed(), IntStream Stream<Integer> : -

    Map<String, Object> map = IntStream.range(0, values.length).boxed()
               .collect(Collectors.toMap(i -> "X" + i, i -> values[i], (a, b) -> b));
    
  • , @Holger, forEach , IntStream.collect three-arg : -

    Map<String, Object> map = IntStream.range(0, values.length)
               .collect(HashMap::new, (m,i) -> m.put("X"+i,values[i]), Map::putAll);
    
+2

All Articles