Collecting value of int array using normal JAVA Stream
You can solve your issue like so :
String output = Arrays.stream(arr)
.boxed()
.map(String::valueOf)
.collect(Collectors.joining(",")); // 0,1,8,10,12,56,78
Explain what happen :
when you use Arrays.asList()
which look :
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
it took varargs of type T
, in your case you use it for int[]
Object, so Arrays.asList()
will return List
of int[]
and not a stream of ints, so instead you have to use Arrays.stream
which look like this :
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
to get the correct data.
Arrays.asList(arr)
returns a List<int[]>
whose only element is arr
. Therefore streaming that List
and then mapping that single element to String.valueOf(x)
and collecting with Collectors.joining(",")
will result in a String
whose value is that single array's toString()
, which is the output you see.
String output = Arrays.asList(arr) // List<int[]>
.stream() // Stream<int[]>
.map(x -> String.valueOf(x)) // Stream<String> having a single element - "[I@776ec8df"
.collect(Collectors.joining(",")); // "[I@776ec8df"
When you create an IntStream
from the int
array, you get a stream of the individual elements (the int
values), so you can box them, convert then to String
s and join them to get the desired output.
You can make your first snippet work if you change:
int arr[] = new int[] {10,1,56,8,78,0,12};
to:
Integer arr[] = new Integer[] {10,1,56,8,78,0,12};
since this way Arrays.asList(arr)
will produce a List<Integer>
containing all the elements of the input array.