Java Streams: Issue about collect to a Map<String, Object>

Jordi :

I'm running against an issue:

I've created this stream I need to map to a Map<String, Object>:

private Map<String, Object> collectArguments(JoinPoint point) {
    CodeSignature signature = (CodeSignature) point.getSignature();
    String[] argNames = signature.getParameterNames();
    Object[] args = point.getArgs();

    return IntStream.range(0, args.length)
        .collect(Collectors.toMap(param -> argNames[param], param -> args[param]));
}

I'm getting the following message, which I don't quite figure out:

[Java] Type mismatch: cannot convert from Collector<Object,capture#3-of ?,Map<Object,Object>> to Supplier<R>
Eran :

IntStream doesn't have a collect method that accepts a Collector. It only has a 3 argument collect method having this signature:

<R> R collect(Supplier<R> supplier,
              ObjIntConsumer<R> accumulator,
              BiConsumer<R, R> combiner)

Perhaps you should use a Stream<Integer>:

return IntStream.range(0, args.length)
                .boxed()
                .collect(Collectors.toMap(param -> argNames[param],
                                          param -> args[param]));

Or, if you wish to use the collect method of IntStream, it would look like this:

return IntStream.range(0, args.length)
                .collect(HashMap::new,
                         (m,i)->m.put(argNames[i],args[i]),
                         (m1,m2)->m1.putAll (m2));

or

return IntStream.range(0, args.length)
                .collect(HashMap::new,
                         (m,i)->m.put(argNames[i],args[i]),
                         Map::putAll);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35999&siteId=1