我有一个IntStream
,想要对该流的每个元素进行一些计算,并将它们作为Map
返回,其中键是 int 值,值是计算结果。我编写了以下代码:
Map<Integer, Double> result = intStream
.boxed()
.collect(Collectors.toMap(Function.identity(), element -> {
// calculation logic here
return result;
}));
IntStream.range(0,10)
.collect(
Collectors.toMap(Function.identity(), i -> computeSmth(i)));
当我调用 computeSmth(Integer a)
时,我得到了以下编译器错误。
method collect in interface java.util.stream.IntStream cannot be applied to given types;
required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Map<java.lang.Object,java.lang.String>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
我做错了什么?
IntStream
只有三个参数的collect
方法。你需要将你的toMap
方法改写为三个参数的形式,或者使用.boxed()
将IntStream
转换为Stream<Integer>
。 - Mishaboxed()
。这肯定比mapToObj(Integer::valueOf)
更好。 :-) - C. K. Young