Skip to content

Java print ArrayList example

Java print ArrayList example shows how to print ArrayList in Java. The example also shows various ways to print the ArrayList using a loop, Arrays class, and Java 8 Stream.

How to print ArrayList in Java?

There are several ways using which you can print ArrayList in Java as given below.

1) Using for loop

You can print ArrayList using for loop in Java just like an array.

Output

2) Using enhanced for loop

You can also use the enhanced for loop instead of the for loop it iterate over the elements of an ArrayList and print.

Output

3) Using Arrays class

You can convert ArrayList to an array and use the toString method of Arrays class to print the elements.

Output

If you want to remove the square brackets, you can remove them using the replaceAll method as given below.

Output

4) Using Java 8 stream

If you are using Java 8, you can use the stream as given below.

Or you can use below given statement to print the elements of ArrayList.

Output

How to print ArrayList containing custom objects?

How to print ArrayList containing objects of a custom class? For example, consider below given code containing ArrayList of Person class objects.

Output

Instead of printing the contents of the Person objects, our code printed memory locations of the Person object. The reason is since the Person class does not override the toString method, the default toString method of the Object class is called which prints the address location of the object.

Let’s override the toString method in the Person class to get the contents of the Person object instead of the memory locations.

Output

This example is a part of the Java ArrayList tutorial.

Please let me know your views in the comments section below.

About the author

5 comments

  1. Thank q u RahimV it was help to me I was struck on print of the list for my product class but it was printing class object address when i see your class example i had a changed according to your code Now it is working fine 🙂

Leave a Reply

Your email address will not be published.