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
2
  • How do your Strings become ints in the middle of your operation? Commented May 6, 2015 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 Commented May 6, 2015 at 11:57

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

12

Try this

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

Comments

10

In standard Java

System.out.println(Arrays.deepToString(names));

1 Comment

Very nice, but is there a new way using java 8 features?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.