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

怎甘沉沦 提交于 2021-02-04 21:16:26

问题


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.


回答1:


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.




回答2:


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.




回答3:


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]


来源:https://stackoverflow.com/questions/59454161/stream-2d-array-trim-values-and-collect-back-to-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!