我是第一次尝试 java8 流,并且对类型推断的语法有点困惑。这是片段:
其核心是:
Arrays.stream(stringArray).mapToInt(Integer::parseInt).collect(Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)
这导致:
Error:(56, 84) java: 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.List<java.lang.Object>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
Run Code Online (Sandbox Code Playgroud)
这是一个更完整的片段:
try {
br = new BufferedReader(new FileReader(inputFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
while ((line = br.readLine()) != null) {
list.add(Arrays.stream(line.split(","))
.mapToInt(Integer::parseInt).collect(Collectors.toList()));
}
Run Code Online (Sandbox Code Playgroud)
我尝试过一些类似的方法/调整,但尚未取得突破。提示赞赏。
这根本与类型推断无关,而是IntStream没有collect接受Collector. 相反,您可以调用IntStream#boxed将其映射到 a Stream<Integer>,然后将其收集到 a List<Integer>:
Arrays.stream(stringArray)
.mapToInt(Integer::parseInt)
.boxed()
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
一个更简单的解决方案是将其直接映射到Stream<Integer>:
Arrays.stream(stringArray)
.map(Integer::parseInt)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
633 次 |
| 最近记录: |