Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Loop and Print 2D array using Java 8

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
like image 536
MChaker Avatar asked May 06 '15 00:05

MChaker


People also ask

How do I print a 2D array in one loop?

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.

Can we print 2D array using for each loop?

We can loop through 2D arrays using nested for loops or nested enhanced for each loops.

How do you loop a 2D array?

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.

Can you print a 2D array in Java?

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.


2 Answers

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.

like image 169
Radiodef Avatar answered Sep 18 '22 19:09

Radiodef


Try this

Stream.of(names).map(Arrays::toString).forEach(System.out::println);
like image 39
Paul Boddington Avatar answered Sep 20 '22 19:09

Paul Boddington