我写了这段代码:
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String... args) {
List<String> a = Arrays.asList("One", "Two", "three");
List<Integer> lengths = a.stream().mapToInt(String::length).collect(Collectors.toList());
}
}
但它不想编译,说:
Error:(8, 68) 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)
这里发生了什么?为什么有限制?如果你使用 map 。而不是mapToInt,它工作得很好。
最佳答案
mapToInt
产生 IntStream
,其中没有 collect
采取单一的方法Collector
论证。
由于最终结果是 List<Integer>
,您不必转换 Stream
到IntStream
:
List<Integer> lengths = a.stream().map(String::length).collect(Collectors.toList());
转变Stream
到IntStream
如果您想收集 Stream
的元素,那就有意义了到原始数组:
int[] lengths = a.stream().mapToInt(String::length).toArray();
如果你想转变成IntStream
并仍然使用collect
方法,您可以编写以下内容(不太推荐):
List<Integer> lengths =
a.stream()
.mapToInt(String::length)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
关于java - 为什么mapToInt不能与collect(toList())一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50552258/