我有一个int流,并希望该流的每个元素进行一些计算,并将它们作为Map返回,其中键是int值,值是该计算的结果.我写了下面这段代码:
IntStream.range(0,10).collect(Collectors.toMap(Function.identity(), i -> computeSmth(i)));
Run Code Online (Sandbox Code Playgroud)
哪里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)
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
Noo*_*waz 21
这是我的代码,它适合你.
功能参考版本
public class AppLauncher {
public static void main(String a[]){
Map<Integer,Integer> map = IntStream.range(1,10).boxed().collect(Collectors.toMap(Function.identity(),AppLauncher::computeSmth));
System.out.println(map);
}
public static Integer computeSmth(Integer i){
return i*i;
}
}
Run Code Online (Sandbox Code Playgroud)
Lambda表达版本
public class AppLauncher {
public static void main(String a[]){
Map<Integer,Integer> map = IntStream.range(1,10).boxed().collect(Collectors.toMap(Function.identity(),i->i*i));
System.out.println(map);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7592 次 |
最近记录: |