13

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
MChaker
  • 2,610
  • 2
  • 22
  • 38
  • How do your `String`s become `int`s in the middle of your operation? – Holger May 06 '15 at 10:40
  • Ooops sorry. I have edited the code from `for (int[] a : names) { for (int i : a) { System.out.println(i); } }` to `for (String[] a : names) { for (String s : a) { System.out.println(s); } }` Thanks @Holger – MChaker May 06 '15 at 11:57

4 Answers4

23

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.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
12

Try this

Stream.of(names).map(Arrays::toString).forEach(System.out::println);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
10

In standard Java

System.out.println(Arrays.deepToString(names));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

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
drac_o
  • 427
  • 5
  • 11