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

Muhammad Yojer :

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?

David Conrad :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=467349&siteId=1