Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an 2D int array into a 2D String array with Streams?

I am attempting to convert a 2D int array into a 2D String array with this code:

Arrays.stream(intArray).map(a -> 
    Arrays.stream(a).map(i -> 
        Integer.toString(i)).toArray()).toArray(String[][]::new);

but I get the compile-time error cannot convert from String to int when doing Integer.toString(i). I thought it could be because I'm collecting the results of streaming an int array in a String array, but doesn't map create a new Collection?

like image 231
Muhammad Yojer Avatar asked Jun 05 '17 21:06

Muhammad Yojer


1 Answers

Arrays.stream on an int[] returns an IntStream, and to go from an int to a String or any other Object, you have to use the IntStream.mapToObj method, not the map method:

Arrays.stream(intArray).map(a -> 
    Arrays.stream(a).mapToObj(i -> 
        Integer.toString(i)).toArray(String[]::new)).toArray(String[][]::new);

The map method of IntStream is only used to map from an int to an int.

like image 188
David Conrad Avatar answered Nov 15 '22 06:11

David Conrad