Consider this two dimentional array
String[][] names = { {"Sam", "Smith"},
{"Robert", "Delgro"},
{"James", "Gosling"},
};
Using the classic way, if we want to access each element of a two dimensional array, then we need to iterate through two dimensional array using two for loops.
for (String[] a : names) {
for (String s : a) {
System.out.println(s);
}
}
Is there a new elegant way to loop and Print 2D array using Java 8 features (Lambdas,method reference,Streams,...)?
What I have tried so far is this:
Arrays.asList(names).stream().forEach(System.out::println);
Output:
[Ljava.lang.String;@6ce253f1
[Ljava.lang.String;@53d8d10a
[Ljava.lang.String;@e9e54c2
Iterate a loop over the range [0, N * M] using the variable i. At each iteration, find the index of the current row and column as row = i / M and column = i % M respectively. In the above steps, print the value of mat[row][column] to get the value of the matrix at that index.
We can loop through 2D arrays using nested for loops or nested enhanced for each loops.
In order to loop over a 2D array, we first go through each row, and then again we go through each column in every row. That's why we need two loops, nested in each other. Anytime, if you want to come out of the nested loop, you can use the break statement.
Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays. deepToString() method, etc. Each approach follows a different procedure, but all of them can still accomplish the same goal, i.e., printing a 2D array.
Keeping the same output as your for
loops:
Stream.of(names)
.flatMap(Stream::of)
.forEach(System.out::println);
(See Stream#flatMap
.)
Also something like:
Arrays.stream(names)
.map(a -> String.join(" ", a))
.forEach(System.out::println);
Which produces output like:
Sam Smith Robert Delgro James Gosling
(See String#join
.)
Also:
System.out.println(
Arrays.stream(names)
.map(a -> String.join(" ", a))
.collect(Collectors.joining(", "))
);
Which produces output like:
Sam Smith, Robert Delgro, James Gosling
(See Collectors#joining
.)
Joining is one of the less discussed but still wonderful new features of Java 8.
Try this
Stream.of(names).map(Arrays::toString).forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With