How to convert a 2D array to a 2D String array with streams?

I am trying to convert a 2D int array to a 2D String array using this code:

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

but when I execute Integer.toString(i) I get a compile-time error cannot convert from String to int . I thought this could be because I am collecting the results of streaming an int array in a String array, but does not map create a new Collection ?

+5
source share
1 answer

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

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

The map method IntStream used only for displaying from int to int .

+10
source

Source: https://habr.com/ru/post/1268567/


All Articles