打印Java数组的最简单方法是什么?

时间:2022-04-11 11:49:28

In Java, arrays don't override toString(), so if you try to print one directly, you get the className + @ + the hex of the hashCode of the array, as defined by Object.toString():

在Java中,数组不覆盖toString(),因此,如果您试图直接打印一个,那么就会得到Object.toString()所定义的数组hashCode的类名+ @ + hex。

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray);     // prints something like '[I@3343c8b3'

But usually we'd actually want something more like [1, 2, 3, 4, 5]. What's the simplest way of doing that? Here are some example inputs and outputs:

但是通常我们想要的东西更像[1,2,3,4,5]。最简单的方法是什么?以下是一些输入和输出示例:

// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]

26 个解决方案

#1


1917  

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

从Java 5开始,您可以使用Arrays.toString(arr)或Arrays.deepToString(arr)来处理数组中的数组。注意,在数组中每个对象上的对象[]版本调用。tostring()。输出甚至以你想要的方式进行装饰。

Examples:

例子:

Simple Array:

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));

Output:

输出:

[John, Mary, Bob]

Nested Array:

String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));

Output:

输出:

[[John, Mary], [Alice, Bob]]

double Array:

double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));

Output:

输出:

[7.0, 9.0, 5.0, 1.0, 3.0 ]

int Array:

int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));

Output:

输出:

[7, 9, 5, 1, 3 ]

#2


290  

Always check the standard libraries first. Try:

一定要先检查标准库。试一试:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

或者,如果数组包含其他数组作为元素:

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

#3


80  

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

但是,这很好,因为“总是先检查标准库”,我不会偶然发现数组的技巧。toString(myarray)

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

——因为我专注于myarray的类型,看看如何做到这一点。我不想重复这个东西:我想要一个简单的调用,使它与我在Eclipse调试器和myarray.toString()中看到的结果类似。

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

#4


64  

In JDK1.8 you can use aggregate operations and a lambda expression:

在JDK1.8中,可以使用聚合操作和lambda表达式:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/

#5


35  

If you're using Java 1.4, you can instead do:

如果您使用的是Java 1.4,则可以这样做:

System.out.println(Arrays.asList(array));

(This works in 1.5+ too, of course.)

(当然,这也适用于1.5+。)

#6


29  

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

从Java 8开始,您还可以利用String类提供的join()方法来打印数组元素,而不需要括号,并由一个选择分隔符分隔(这是下面示例的空格字符):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

The output will be "Hey there amigo!".

输出将是“嘿,amigo!”

#7


23  

Arrays.deepToString(arr) only prints on one line.

deeptostring (arr)只在一行上打印。

int[][] table = new int[2][2];

To actually get a table to print as a two dimensional table, I had to do this:

为了让一个表格打印成二维表格,我必须这样做:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

It seems like the Arrays.deepToString(arr) method should take a separator string, but unfortunately it doesn't.

似乎Arrays.deepToString(arr)方法应该采用分隔符字符串,但不幸的是它没有。

#8


23  

Arrays.toString

As a direct answer, the solution provided by several, including @Esko, using the Arrays.toString and Arrays.deepToString methods, is simply the best.

作为直接的答案,由几个人(包括@Esko)提供的解决方案使用了数组。toString和Arrays.deepToString方法是最好的。

Java 8 - Stream.collect(joining()), Stream.forEach

Below I try to list some of the other methods suggested, attempting to improve a little, with the most notable addition being the use of the Stream.collect operator, using a joining Collector, to mimic what the String.join is doing.

下面我试着列出一些其他的方法,试图改进一些,其中最值得注意的是使用流。收集操作符,使用连接收集器来模拟字符串。加入。

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);

#9


20  

Prior to Java 8 we could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays. We have got the option of Stream and lambda in Java 8 which can also be used for the printing the array.

在Java 8之前,我们可以使用Arrays.toString(数组)来打印一维数组和Arrays.deepToString(数组)来实现多维数组。我们已经得到了流和lambda在Java 8中的选项,它也可以用于打印数组。

Printing One dimensional Array:

打印一维数组:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

The output is:

的输出是:

[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob

[1,2,3,4,5][约翰,玛丽,鲍勃]1 2 3 4 5约翰玛丽鲍勃。

Printing Multi-dimensional Array Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array) as:

打印多维数组,以防我们想要打印多维数组,我们可以使用Arrays.deepToString(数组):

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

Now the point to observe is that the method Arrays.stream(T[]), which in case of int[] returns us Stream<int[]> and then method flatMapToInt() maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

现在要注意的是,方法Arrays.stream(T[]),在int[]的情况下,它返回us Stream ,然后方法flatMapToInt()将流的每个元素映射到一个映射流的内容,并将提供的映射函数应用到每个元素。 []>

The output is:

的输出是:

[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson

(约翰,b .) [[j] . [j] . [[j] . [j] . [[j] . [[j] . [j] . [j] . [[j] . [j] . [[j] . [j] . [[j] . [j] . [[j] . [[j]]。

#10


17  

for(int n: someArray) {
    System.out.println(n+" ");
}

#11


15  

Different Ways to Print Arrays in Java:

在Java中打印数组的不同方法:

  1. Simple Way

    简单的方法

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    

Output: [One, Two, Three, Four]

输出:[1,2,3,4]

  1. Using toString()

    使用toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    

Output: [One, Two, Three, Four]

输出:[1,2,3,4]

  1. Printing Array of Arrays

    打印数组的数组

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    

Output: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c] [[Fifth, Sixth], [Seventh, Eighth]]

输出:[[Ljava.lang.String;@1ad086a] [Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c][[第五,第六],[第七,第八]]

Resource: Access An Array

资源:访问数组

#12


12  

Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray

在我看来,使用正则for循环是打印数组的最简单方法。这里有一个基于您的intArray的示例代码。

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours 1, 2, 3, 4, 5

它给出的输出是1 2 3 4 5。

#13


7  

I came across this post in Vanilla #Java recently. It's not very convenient writing Arrays.toString(arr);, then importing java.util.Arrays; all the time.

我最近遇到了这篇文章。编写Arrays.toString(arr),然后导入java.util. array并不是很方便;所有的时间。

Please note, this is not a permanent fix by any means. Just a hack that can make debugging simpler.

请注意,这不是一个永久的修复方法。只是一个可以使调试更简单的hack。

Printing an array directly gives the internal representation and the hashCode. Now, all classes have Object as the parent-type. So, why not hack the Object.toString()? Without modification, the Object class looks like this:

直接打印数组会给出内部表示和hashCode。现在,所有类都有对象作为父类。那么,为什么不修改Object.toString()呢?如果不修改,对象类是这样的:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

What if this is changed to:

如果改成:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This modded class may simply be added to the class path by adding the following to the command line: -Xbootclasspath/p:target/classes.

通过将以下命令添加到命令行:-Xbootclasspath/p:target/类,可以简单地将这个modded类添加到类路径中。

Now, with the availability of deepToString(..) since Java 5, the toString(..) can easily be changed to deepToString(..) to add support for arrays that contain other arrays.

现在,随着deepToString(..)的可用性,由于Java 5, toString(..)可以很容易地更改为deepToString(..),以添加对包含其他数组的数组的支持。

I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a System.outor a PrintWriter for such eventualities.

我发现这是一个非常有用的hack,如果Java可以简单地添加它,那就太棒了。我理解具有非常大数组的潜在问题,因为字符串表示可能会有问题。可能会传递一个系统。为这样的不测事件准备了一个PrintWriter。

#14


7  

It should always work whichever JDK version you use:

它应该始终工作于您所使用的JDK版本:

System.out.println(Arrays.asList(array));

It will work if the Array contains Objects. If the Array contains primitive types, you can use wrapper classes instead storing the primitive directly as..

如果数组包含对象,它就会工作。如果数组包含基本类型,则可以使用包装器类,而直接将原语存储为..

Example:

例子:

int[] a = new int[]{1,2,3,4,5};

Replace it with:

换成:

Integer[] a = new Integer[]{1,2,3,4,5};

Update :

更新:

Yes ! this is to be mention that converting an array to an object array OR to use the Object's array is costly and may slow the execution. it happens by the nature of java called autoboxing.

是的!这需要说明的是,将数组转换为对象数组或使用对象数组的代价很高,并且可能会降低执行速度。这是由java的性质称为自动装箱。

So only for printing purpose, It should not be used. we can make a function which takes an array as parameter and prints the desired format as

所以只有打印的目的,它不应该被使用。我们可以创建一个函数,它以数组作为参数,并输出所需的格式。

public void printArray(int [] a){
        //write printing code
} 

#15


7  

In java 8 it is easy. there are two keywords

在java 8中,这很简单。有两个关键词

  1. stream: Arrays.stream(intArray).forEach
  2. 流:Arrays.stream .forEach(intArray)
  3. method reference: ::println

    方法参考:::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

If you want to print all elements in the array in the same line, then just use print instead of println i.e.

如果您想要在同一行中打印数组中的所有元素,那么只需使用print而不是println。

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Another way without method reference just use:

另一种没有方法引用的方法是:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));

#16


6  

There's one additional way if your array is of type char[]:

如果您的数组是char类型,还有一种方法[]:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

打印

abc

#17


5  

A simplified shortcut I've tried is this:

我尝试过的简化的捷径是:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

It will print

它将打印

1
2
3

No loops required in this approach and it is best for small arrays only

这种方法不需要循环,对小数组最好。

#18


4  

To add to all the answers, printing the object as a JSON string is also an option.

要添加所有的答案,将对象作为JSON字符串打印也是一个选项。

Using Jackson:

杰克逊使用:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Using Gson:

使用Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));

#19


4  

public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }

#20


4  

You could loop through the array, printing out each item, as you loop. For example:

您可以循环遍历数组,将每个条目打印出来。例如:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Output:

输出:

item 1
item 2
item 3

#21


3  

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

join(*)方法可以是一个选项,例如:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

我使用了以下依赖项。

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

#22


3  

There Are Following way to print Array

下面是打印数组的方法。

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(Integer lists : arrayInt){
         System.out.println(lists);
     }

#23


3  

For-each loop can also be used to print elements of array:

For-each循环还可以用于打印数组元素:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);

#24


1  

// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(intArray));

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

System.out.println(Arrays.toString(strArray));

output: [John, Mary, Bob]

#25


-3  

You could use Arrays.toString()

您可以使用Arrays.toString()

String[] array = { "a", "b", "c" };  
System.out.println(Arrays.toString(array));

#26


-5  

The simplest way to print an array is to use a for-loop:

打印数组的最简单方法是使用for循环:

// initialize array
for(int i=0;i<array.length;i++)
{
    System.out.print(array[i] + " ");
}

#1


1917  

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

从Java 5开始,您可以使用Arrays.toString(arr)或Arrays.deepToString(arr)来处理数组中的数组。注意,在数组中每个对象上的对象[]版本调用。tostring()。输出甚至以你想要的方式进行装饰。

Examples:

例子:

Simple Array:

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));

Output:

输出:

[John, Mary, Bob]

Nested Array:

String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));

Output:

输出:

[[John, Mary], [Alice, Bob]]

double Array:

double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));

Output:

输出:

[7.0, 9.0, 5.0, 1.0, 3.0 ]

int Array:

int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));

Output:

输出:

[7, 9, 5, 1, 3 ]

#2


290  

Always check the standard libraries first. Try:

一定要先检查标准库。试一试:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

或者,如果数组包含其他数组作为元素:

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

#3


80  

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

但是,这很好,因为“总是先检查标准库”,我不会偶然发现数组的技巧。toString(myarray)

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

——因为我专注于myarray的类型,看看如何做到这一点。我不想重复这个东西:我想要一个简单的调用,使它与我在Eclipse调试器和myarray.toString()中看到的结果类似。

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

#4


64  

In JDK1.8 you can use aggregate operations and a lambda expression:

在JDK1.8中,可以使用聚合操作和lambda表达式:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/

#5


35  

If you're using Java 1.4, you can instead do:

如果您使用的是Java 1.4,则可以这样做:

System.out.println(Arrays.asList(array));

(This works in 1.5+ too, of course.)

(当然,这也适用于1.5+。)

#6


29  

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

从Java 8开始,您还可以利用String类提供的join()方法来打印数组元素,而不需要括号,并由一个选择分隔符分隔(这是下面示例的空格字符):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

The output will be "Hey there amigo!".

输出将是“嘿,amigo!”

#7


23  

Arrays.deepToString(arr) only prints on one line.

deeptostring (arr)只在一行上打印。

int[][] table = new int[2][2];

To actually get a table to print as a two dimensional table, I had to do this:

为了让一个表格打印成二维表格,我必须这样做:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

It seems like the Arrays.deepToString(arr) method should take a separator string, but unfortunately it doesn't.

似乎Arrays.deepToString(arr)方法应该采用分隔符字符串,但不幸的是它没有。

#8


23  

Arrays.toString

As a direct answer, the solution provided by several, including @Esko, using the Arrays.toString and Arrays.deepToString methods, is simply the best.

作为直接的答案,由几个人(包括@Esko)提供的解决方案使用了数组。toString和Arrays.deepToString方法是最好的。

Java 8 - Stream.collect(joining()), Stream.forEach

Below I try to list some of the other methods suggested, attempting to improve a little, with the most notable addition being the use of the Stream.collect operator, using a joining Collector, to mimic what the String.join is doing.

下面我试着列出一些其他的方法,试图改进一些,其中最值得注意的是使用流。收集操作符,使用连接收集器来模拟字符串。加入。

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);

#9


20  

Prior to Java 8 we could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays. We have got the option of Stream and lambda in Java 8 which can also be used for the printing the array.

在Java 8之前,我们可以使用Arrays.toString(数组)来打印一维数组和Arrays.deepToString(数组)来实现多维数组。我们已经得到了流和lambda在Java 8中的选项,它也可以用于打印数组。

Printing One dimensional Array:

打印一维数组:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

The output is:

的输出是:

[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob

[1,2,3,4,5][约翰,玛丽,鲍勃]1 2 3 4 5约翰玛丽鲍勃。

Printing Multi-dimensional Array Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array) as:

打印多维数组,以防我们想要打印多维数组,我们可以使用Arrays.deepToString(数组):

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

Now the point to observe is that the method Arrays.stream(T[]), which in case of int[] returns us Stream<int[]> and then method flatMapToInt() maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

现在要注意的是,方法Arrays.stream(T[]),在int[]的情况下,它返回us Stream ,然后方法flatMapToInt()将流的每个元素映射到一个映射流的内容,并将提供的映射函数应用到每个元素。 []>

The output is:

的输出是:

[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson

(约翰,b .) [[j] . [j] . [[j] . [j] . [[j] . [[j] . [j] . [j] . [[j] . [j] . [[j] . [j] . [[j] . [j] . [[j] . [[j]]。

#10


17  

for(int n: someArray) {
    System.out.println(n+" ");
}

#11


15  

Different Ways to Print Arrays in Java:

在Java中打印数组的不同方法:

  1. Simple Way

    简单的方法

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    

Output: [One, Two, Three, Four]

输出:[1,2,3,4]

  1. Using toString()

    使用toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    

Output: [One, Two, Three, Four]

输出:[1,2,3,4]

  1. Printing Array of Arrays

    打印数组的数组

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    

Output: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c] [[Fifth, Sixth], [Seventh, Eighth]]

输出:[[Ljava.lang.String;@1ad086a] [Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c][[第五,第六],[第七,第八]]

Resource: Access An Array

资源:访问数组

#12


12  

Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray

在我看来,使用正则for循环是打印数组的最简单方法。这里有一个基于您的intArray的示例代码。

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours 1, 2, 3, 4, 5

它给出的输出是1 2 3 4 5。

#13


7  

I came across this post in Vanilla #Java recently. It's not very convenient writing Arrays.toString(arr);, then importing java.util.Arrays; all the time.

我最近遇到了这篇文章。编写Arrays.toString(arr),然后导入java.util. array并不是很方便;所有的时间。

Please note, this is not a permanent fix by any means. Just a hack that can make debugging simpler.

请注意,这不是一个永久的修复方法。只是一个可以使调试更简单的hack。

Printing an array directly gives the internal representation and the hashCode. Now, all classes have Object as the parent-type. So, why not hack the Object.toString()? Without modification, the Object class looks like this:

直接打印数组会给出内部表示和hashCode。现在,所有类都有对象作为父类。那么,为什么不修改Object.toString()呢?如果不修改,对象类是这样的:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

What if this is changed to:

如果改成:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This modded class may simply be added to the class path by adding the following to the command line: -Xbootclasspath/p:target/classes.

通过将以下命令添加到命令行:-Xbootclasspath/p:target/类,可以简单地将这个modded类添加到类路径中。

Now, with the availability of deepToString(..) since Java 5, the toString(..) can easily be changed to deepToString(..) to add support for arrays that contain other arrays.

现在,随着deepToString(..)的可用性,由于Java 5, toString(..)可以很容易地更改为deepToString(..),以添加对包含其他数组的数组的支持。

I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a System.outor a PrintWriter for such eventualities.

我发现这是一个非常有用的hack,如果Java可以简单地添加它,那就太棒了。我理解具有非常大数组的潜在问题,因为字符串表示可能会有问题。可能会传递一个系统。为这样的不测事件准备了一个PrintWriter。

#14


7  

It should always work whichever JDK version you use:

它应该始终工作于您所使用的JDK版本:

System.out.println(Arrays.asList(array));

It will work if the Array contains Objects. If the Array contains primitive types, you can use wrapper classes instead storing the primitive directly as..

如果数组包含对象,它就会工作。如果数组包含基本类型,则可以使用包装器类,而直接将原语存储为..

Example:

例子:

int[] a = new int[]{1,2,3,4,5};

Replace it with:

换成:

Integer[] a = new Integer[]{1,2,3,4,5};

Update :

更新:

Yes ! this is to be mention that converting an array to an object array OR to use the Object's array is costly and may slow the execution. it happens by the nature of java called autoboxing.

是的!这需要说明的是,将数组转换为对象数组或使用对象数组的代价很高,并且可能会降低执行速度。这是由java的性质称为自动装箱。

So only for printing purpose, It should not be used. we can make a function which takes an array as parameter and prints the desired format as

所以只有打印的目的,它不应该被使用。我们可以创建一个函数,它以数组作为参数,并输出所需的格式。

public void printArray(int [] a){
        //write printing code
} 

#15


7  

In java 8 it is easy. there are two keywords

在java 8中,这很简单。有两个关键词

  1. stream: Arrays.stream(intArray).forEach
  2. 流:Arrays.stream .forEach(intArray)
  3. method reference: ::println

    方法参考:::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

If you want to print all elements in the array in the same line, then just use print instead of println i.e.

如果您想要在同一行中打印数组中的所有元素,那么只需使用print而不是println。

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Another way without method reference just use:

另一种没有方法引用的方法是:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));

#16


6  

There's one additional way if your array is of type char[]:

如果您的数组是char类型,还有一种方法[]:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

打印

abc

#17


5  

A simplified shortcut I've tried is this:

我尝试过的简化的捷径是:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

It will print

它将打印

1
2
3

No loops required in this approach and it is best for small arrays only

这种方法不需要循环,对小数组最好。

#18


4  

To add to all the answers, printing the object as a JSON string is also an option.

要添加所有的答案,将对象作为JSON字符串打印也是一个选项。

Using Jackson:

杰克逊使用:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Using Gson:

使用Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));

#19


4  

public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }

#20


4  

You could loop through the array, printing out each item, as you loop. For example:

您可以循环遍历数组,将每个条目打印出来。例如:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Output:

输出:

item 1
item 2
item 3

#21


3  

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

join(*)方法可以是一个选项,例如:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

我使用了以下依赖项。

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

#22


3  

There Are Following way to print Array

下面是打印数组的方法。

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(Integer lists : arrayInt){
         System.out.println(lists);
     }

#23


3  

For-each loop can also be used to print elements of array:

For-each循环还可以用于打印数组元素:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);

#24


1  

// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(intArray));

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

System.out.println(Arrays.toString(strArray));

output: [John, Mary, Bob]

#25


-3  

You could use Arrays.toString()

您可以使用Arrays.toString()

String[] array = { "a", "b", "c" };  
System.out.println(Arrays.toString(array));

#26


-5  

The simplest way to print an array is to use a for-loop:

打印数组的最简单方法是使用for循环:

// initialize array
for(int i=0;i<array.length;i++)
{
    System.out.print(array[i] + " ");
}