如何使用 Java 8 循环和打印二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30065577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:22:19  来源:igfitidea点击:

How to Loop and Print 2D array using Java 8

javamultidimensional-arrayjava-8

提问by MChaker

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 循环来遍历二维数组。

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,...)?

是否有一种新的优雅方式来使用 Java 8 功能(Lambdas、方法参考、Streams 等)循环和打印 2D 数组?

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

回答by Radiodef

Keeping the same output as your forloops:

保持与for循环相同的输出:

Stream.of(names)
    .flatMap(Stream::of)
        .forEach(System.out::println);

(See Stream#flatMap.)

(见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.)

(见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.)

(见Collectors#joining。)

Joining is one of the less discussed but still wonderful new features of Java 8.

加入是 Java 8 中讨论较少但仍然很棒的新特性之一。

回答by Reimeus

In standard Java

在标准 Java 中

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

回答by Paul Boddington

Try this

试试这个

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