How to copy and print a 2D array using Java 8

Consider this two dimensional array

String[][] names = { {"Sam", "Smith"}, {"Robert", "Delgro"}, {"James", "Gosling"}, }; 

Using the classical method, if we want to access each element of a two-dimensional array, we need to iterate through the 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 a 2D array using Java 8 features (Lambdas, method reference, threads, ...)?

What I have tried so far is the following:

 Arrays.asList(names).stream().forEach(System.out::println); 

Conclusion:

 [Ljava.lang.String;@6ce253f1 [Ljava.lang.String;@53d8d10a [Ljava.lang.String;@e9e54c2 
+5
source share
3 answers

Keeping the same result as for contours:

 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); 

What produces the output, for example:

  Sam smith
 Robert Delgro
 James gosling 

(see String#join .)

also:

 System.out.println( Arrays.stream(names) .map(a -> String.join(" ", a)) .collect(Collectors.joining(", ")) ); 

What produces the output, for example:

  Sam Smith, Robert Delgro, James Gosling 

(see Collectors#joining .)

Joining is one of the less talked about, but still great new features in Java 8.

+14
source

In standard Java

 System.out.println(Arrays.deepToString(names)); 
+7
source

try it

 Stream.of(names).map(Arrays::toString).forEach(System.out::println); 
+6
source

All Articles