Reputation: 2649
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
Upvotes: 13
Views: 19545
Reputation: 437
With Java 8 using Streams
and forEach
:
Arrays.stream(names).forEach((i) -> {
Arrays.stream(i).forEach((j) -> System.out.print(j + " "));
System.out.println();
});
The first forEach
acts as outer loop while the next as inner loop.
This gives the following output:
Sam Smith
Robert Delgro
James Gosling
Upvotes: 1
Reputation: 37845
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.
Upvotes: 23
Reputation: 37645
Try this
Stream.of(names).map(Arrays::toString).forEach(System.out::println);
Upvotes: 12
Reputation: 159774
In standard Java
System.out.println(Arrays.deepToString(names));
Upvotes: 10