Reputation: 59
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
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).
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
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
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