Replace null by another value in 2D String array using Java 8 Stream

Viewed 460

I want to replace null value by string Z in two dimensional array. I have data like this:

String[][] userData = { { "User A", "A" }, { null, null }, { "User B", "B" } };

Now I need to change this userData like below:

String[][] userData = { { "User A", "A" }, { "Z", "Z" }, { "User B", "B" } };

How do I achieve this by java 8 stream and get back the result in same format (2D string array) ?

3 Answers

Instead of trying to use a lambda expression to regenerate the entire array you could use a pair of IntStream.range(int, int) calls to generate the valid array indices and then use a single forEach to replace any null(s). Like,

String[][] userData = { { "User A", "A" }, { null, null }, { "User B", "B" } };
IntStream.range(0, userData.length).forEach(x -> 
            IntStream.range(0, userData[x].length).forEach(y -> {
    if (userData[x][y] == null) {
        userData[x][y] = "Z";
    }
}));
System.out.println(Arrays.deepToString(userData));

Outputs (as requested)

[[User A, A], [Z, Z], [User B, B]]

Check If this works for you

        String[][] userData = {{"User A", "A" }, {null, null}, {"User B", "B" }};
        userData = Arrays.stream(userData).map(arr -> Arrays.stream(arr)
            .map(a -> a!=null ? a : "Z").toArray(String[]::new)).toArray(String[][]::new);

        System.out.println(Arrays.deepToString(userData));
        //[[User A, A], [Z, Z], [User B, B]]

I am suggesting a solution without using stream, but requires java 8+.

( List.replaceAll was introduced in java 8 which accepts a UnaryOperator which would be applied to each element of the list)

String[] replace = {null, null};
String[] replaceWith = { "Z", "Z" };

List<String[]> list = Arrays.asList(userData);
list.replaceAll(arr -> Arrays.equals(arr, replace) ? replaceWith : arr);
System.out.println(Arrays.deepToString(list.toArray()));

Output:

[[User A, A], [Z, Z], [User B, B]]
Related