Danil Tk
Danil Tk

Reputation: 59

Stream 2d array, trim values and collect back to 2d array

Any idea how to perform a trim operation on a 2d array of strings e.g. 3x3 using Java stream API and collect one back to same dimension 3x3 array?

The point is to avoid using explicit for loops.

The current solution would be simply to do a for loop like:

String arr[][] = {
        {"  word  ", "  word  "},
        {"  word  ", "  word  "},
        {"  word  ", "  word  "}};

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        arr[i][j] = arr[i][j].trim();
    }
}

And that works, but I'm trying to come up with a way to do same with the streaming API.

Upvotes: 0

Views: 301

Answers (3)

Anonymous
Anonymous

Reputation: 86333

Please first decide whether you prefer to create a new 2D array with the same dimensions or you want to store your trimmed strings back into the existing array. Both are possible and neither is hard to do (when you now how).

  • Your question may sound more like you want a new array with the same dimensions. If so, I find streams fine for the job and recommend the answer by Ravinfra Ranwala, it is just fine.
  • Your code in the questions stores the trimmed strings back into the existing array. If you want this and don’t want to use loops, I recommend that you don’t use streams either, but List.replaceAll​():
    String arr[][] = {
            {"  word  ", "  word  "},
            {"  word  ", "  word  "},
            {"  word  ", "  word  "}};
    
    Arrays.asList(arr).forEach(inner ->
            Arrays.asList(inner).replaceAll(String::trim));
    
    System.out.println(Arrays.deepToString(arr));
    
    Output from this snippet is:
    [[word, word], [word, word], [word, word]]
    

Arrays.asList() makes a list view unto your array. Changes to the list write back into the array, which is what we wanted.

Upvotes: 1

user14940971
user14940971

Reputation:

You can process the current array without creating a new one using IntStream.forEach method:

String[][] arr = {
        {"  word  ", "  word  "},
        {"  word  ", "  word  "},
        {"  word  ", "  word  "}};

IntStream.range(0, arr.length)
        .forEach(i -> IntStream.range(0, arr[i].length)
                .forEach(j -> arr[i][j] = arr[i][j].trim()));

// output
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);

Output:

[word, word]
[word, word]
[word, word]

Upvotes: 0

pom
pom

Reputation: 340

You can use Arrays.stream to stream arrays as in:

arr=Arrays.stream(arr).map(s -> Arrays.stream(s).map(a->a.trim()).toArray(String[]::new)).toArray(String[][]::new);

You can stream the 1st dimension first then the second.

Upvotes: 0

Related Questions