从数组流式传输时,为什么我不能将整数映射到字符串?
此代码有效(取自 Javadoc):
This code works (taken in the Javadoc):
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
String commaSeparatedNumbers = numbers.stream()
.map(i -> i.toString())
.collect(Collectors.joining(", "));
这个不能编译:
int[] numbers = {1, 2, 3, 4};
String commaSeparatedNumbers = Arrays.stream(numbers)
.map((Integer i) -> i.toString())
.collect(Collectors.joining(", "));
IDEA 告诉我lambda 表达式中的返回类型字符串不兼容".
IDEA tells me I have an "incompatible return type String in lambda expression".
为什么?以及如何解决这个问题?
Why ? And how to fix that ?
推荐答案
Arrays.stream(int[])
创建一个IntStream
,而不是一个Stream<整数>
.所以你需要调用 mapToObj
在将 int
映射到对象时,而不仅仅是 map
.
Arrays.stream(int[])
creates an IntStream
, not a Stream<Integer>
. So you need to call mapToObj
instead of just map
, when mapping an int
to an object.
这应该可以按预期工作:
This should work as expected:
String commaSeparatedNumbers = Arrays.stream(numbers)
.mapToObj(i -> ((Integer) i).toString()) //i is an int, not an Integer
.collect(Collectors.joining(", "));
你也可以这样写:
String commaSeparatedNumbers = Arrays.stream(numbers)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
相关文章