Java - How to Print an Array in One Line

Introduction

Java is a type-safe, verbose language. There are advantages to this, but also some drawbacks. Namely - there's oftentimes a lot of boilerplate code and simple operations such as printing an array aren't as simple as supplying it to the println() method:

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

This results in the hashes of object reference in memory, not its contents:

[I@7c3df479

This is because Java's arrays don't override the toString() method of the Object class, and just return the hash of the object itself. This is an obviously missing feature in the language, and it's not exactly clear why such a feature would be missing, especially with other languages having support for printing such fundamental data structures.

In this guide, we'll take a look at several ways of printing arrays in one line - utilizing the built-in helper methods and the Stream API, weighing the differences between the approaches and when to use which one.

Arrays.toString()

The simplest and most straightforward way to print an array in a single line is to use the helper Arrays class, residing in the java.util package:

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

Under the hood, it uses a StringBuilder to append each element through a simple for loop, and you get a result you might expect when printing an array as-is:

[1, 2, 3, 4, 5, 6]

Note: This approach fails on nested arrays, in which case, an element is an array, so its reference to the object in memory is added instead of its contents.

So, this 2D array can't be printed with Arrays.toString():

int[][] array = new int[][]{{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}};
System.out.println(Arrays.toString(array));

And results in:

[[I@7c3df479, [I@7106e68e]

Arrays.deepToString()

If you'd like to work with nested arrays, you can use the deepToString() method instead:

int[][] array = new int[][]{{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}};
System.out.println(Arrays.deepToString(array));

This results in the expected output:

[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]

Print Array in One Line with Java Streams

Arrays.toString() and Arrays.toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop. When printing though, you might want to format the output a bit, or perform additional operations on the elements while going through them.

The Stream API was added in Java 8, as one of the first steps in introducing the Functional Programming paradigm into Java. Generally, when printing an array with a Stream, you'll call the forEach() method, though there are multiple ways of obtaining a Stream from an Array.

If you'd like to read more about the forEach() method, read our Guided to Stream.forEach() in Java!

The easiest way to obtain a Stream from an Array is the Stream.of() method, which can be used with other collections as well (but depends on the data type), though you could also use Arrays.stream() (more robust) or convert the array to a list and stream that (a bit redundant though) via Arrays.asList().stream().

From all of these - you'll most likely be using the Arrays.stream() method as it doesn't concern itself with whether the elements are a primitive type or an object, which is a concern when using the Stream.of() method.

With Stream.of(), depending on the data type you're using, you'll either use a Stream or a derived variant, such as IntStream. This is important, lest the code return a hash instead of the contents.

int[] intArray = new int[]{1, 2, 3, 4, 5, 6};
String[] objArray = new String[]{"Java", "Python", "JavaScript"};

// If using Stream.of(), primitive types need to be flatmapped
Stream.of(intArray).flatMapToInt(Arrays::stream).forEach(System.out::print);
IntStream.of(intArray).forEach(System.out::print);
// Stream.of() with objects
Stream.of(objArray).forEach(System.out::print);

// Arrays.stream() works with both primitive types and objects
Arrays.stream(intArray).forEach(System.out::print);
Arrays.stream(objArray).forEach(System.out::print);

// If using asList(), primitive types need to be flatMapped
Arrays.asList(intArray).stream().flatMapToInt(Arrays::stream).forEach(System.out::print);
Arrays.asList(objArray).stream().forEach(System.out::print);
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

These all result in:

123456
JavaPythonJavaScript

Generally speaking, the Arrays.stream() method is the safest one to use and is also the shortest/most readable one.

Although not very stylized right now - using Streams allows you to add any intermediary operation in the pipeline, so if you'd like to collect these with a delimiter, for instance, you could use a Collector:

System.out.println(Arrays.stream(objArray).collect(Collectors.joining(",")));

This results in:

Java,Python,JavaScript

You can get creative here, with multiple operations, such as transforming the values, filtering them and then joining:

String[] objArray = new String[]{"Java", "Python", "JavaScript"};

System.out.println(Arrays.stream(objArray)
        map(String::toUpperCase)
        filter(e -> e.startsWith("J"))
        collect(Collectors.joining(",")));

Which maps all of the elements to their counterparts in upper case, filters given a predicate (that an element starts with "J") and then joins them with a delimiter:

JAVA,JAVASCRIPT

Conclusion

In this guide, we've taken a look at how to print an array in Java in a single line - a feature that's missing by default.

We've taken a look at how to print arrays via the built-in helper methods of the Arrays class, as well as how to utilize the Stream API to customize this process.

Last Updated: November 23rd, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms