Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining stream of ints to a String, typecast problems

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)).

like image 855
user3419559 Avatar asked Mar 20 '14 12:03

user3419559


People also ask

How do I return a stream string?

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.


1 Answers

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.

like image 199
skiwi Avatar answered Nov 15 '22 00:11

skiwi