The following code
String[] values = ...
....
Map map = new HashMap<>();
for (int i = 0; i < values.length; i++) {
map.pu
Not very certain about how intelliJ's suggestion would work there, it seems inconsistent. Just put a
System.out.print(map);
statement between the declaration and loop and then it won't suggest you Replace with collect any further.
While using the IntStream#collect
, the compilation fails for the reason that implementation of collect method expects three specified arguments as visible in the error as well while the
Collectors.toMap(i -> "X" + i, i -> values[i])
would result in only a single argument of type Collector
.
Better way to convert the expression would be though to
either use forEach
Map map;
IntStream.range(0, values.length).forEach(i -> map.put("X" + i, values[i]));
Or use boxed() to convert the IntStream
to Stream
as:-
Map map = IntStream.range(0, values.length).boxed()
.collect(Collectors.toMap(i -> "X" + i, i -> values[i], (a, b) -> b));
Or as suggested by @Holger, you can avoid using forEach and boxing overhead and modify the construct to make use of the IntStream.collect
three-arg variant as:-
Map map = IntStream.range(0, values.length)
.collect(HashMap::new, (m,i) -> m.put("X"+i,values[i]), Map::putAll);