I'm trying to join an array of ints in to a String using streams (e.g. {1, 2, 3}
-> "1, 2, 3"
), but I keep getting compile errors. There seems to be a problem with int/String type conversion.
The array is int[] IntArray = {1, 2, 3, 4}
.
String s1 = Arrays.stream(IntArray)
.map(String::valueOf)
.collect(Collectors.joining(", "));
gives a compile error:
Error:(20, 68) java: incompatible types: bad return type in lambda expression
java.lang.String cannot be converted to int
Replacing the map line with .map(Object::toString)
or .map(n -> Integer.toString(n))
doesn't work either:
Error:(23, 49) java: incompatible types: invalid method reference
method toString in class java.lang.Object cannot be applied to given types
required: no arguments
found: int
reason: actual and formal argument lists differ in length
for .map(Object::toString)
, and the first error for .map(n -> Integer.toString(n))
.
Use findFirst to return the first element of the Stream that passes your filters. It returns an Optional , so you can use orElse() to set a default value in case the Stream is empty.
You need to use:
int[] intArray = {1, 2, 3, 4};
String s1 = Arrays.stream(intArray)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", "));
There is one subtle difference here, which is very important:
mapToObj(String::valueOf)
I map the IntStream
to a Stream<String>
here, if you use the regular map
method, then it only takes an IntUnaryOperator
and thus you must stay within int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With