Collections

Java print ArrayList example

Java print ArrayList example shows how to print ArrayList in Java. Example also shows various ways to print ArrayList.

How to print ArrayList in Java?

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

1) Print ArrayList using for loop

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

Output

2) Print ArrayList using for each loop

You can use for each loop or enhanced for loop to print ArrayList elements as given below.

Output

3) Print ArrayList using Arrays class

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

Output

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

Output

4) Print ArrayList using Java 8 stream

If you are using Java 8, you can use stream to print ArrayList elements as given below.

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

Output

How to print ArrayList containing custom objects?

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

Output

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

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

Output

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *