为什么我不能将整数映射到字符串时从数组流传输? [英] Why can't I map integers to strings when streaming from an array?
本文介绍了为什么我不能将整数映射到字符串时从数组流传输?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这段代码有效(在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< Integer>
。所以你需要调用时,<= c $ c> 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(", "));
你也可以这样写:
which you can also write:
String commaSeparatedNumbers = Arrays.stream(numbers)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
这篇关于为什么我不能将整数映射到字符串时从数组流传输?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文