Print ArrayList in Java

Print ArrayList in java

In this post, we will see how to print ArrayList in java.

Java has Array, and it’s a very powerful data structure, but Array has its own set of limitations. The ArrayList data structure was introduced to overcome these limitations.

Before we proceed with our topic, let me quickly brief you with ArrayList.

ArrayList Introduction

ArrayList is an advanced version of Array, as it allows us to implement resizable arrays. Apart from this, ArrayList is a part of Java collections, and it implements Java List. Though ArrayList is the advanced version of array, ArrayList is less efficient than basic arrays in terms of time optimization.

Since we are not focusing on ArrayList Introduction, I have kept it straight and simple; if you are interested in learning more about ArrayList, you can refer ArrayList in java.

6 Ways to Print ArrayList in Java

Yes, you read it right! Fortunately, there isn’t a single way to print ArrayList elements. Though there are dozens of different ways, I’ll cover the three most popular ones in this guide.

Print ArrayList in java using for loop

In the for loop, we are iterating upto the size() of Arraylist. In each iteration, using the get() method of ArrayList, we are retrieving individual element. Finally, with the help of System.out.println statements, we will print those elements.

Have a look at the illustration:

Output:

Elements of ArrayList are:
Hyundai
Kia
Tesla
MG

Print ArrayList in java using for-each Loop

This method is almost identical to the previous one; the only difference here is that we will use the advanced loop method. So, instead of the basic for loop, we will implement its advanced version with some different attributes.

Refer to the illustration below:

Output:

Elements of ArrayList are:
India
Australia
Sudan
Norway

If you look at the above two methods, you will notice only a few noticeable differences, but in terms of working, both these methods are very different.

In the first method, for loop was retrieving the total size, and using that size, the index was evaluated, and later element was accessed. But in this method, every ArrayList element is directly assessed serially using a String variable.

💡 Did you know?

You can not modify ArrayList while iterating using for each loop, Otherwise it will throw Exception.

Print ArrayList in java using iterator framework

So far, we have used basic loop concepts to print the ArrayList element, but in this method, we will use the Iterators; these are a part of the java collection framework. In this method, we are going to use the following method of Interators

  • Iterator(): it returns an iterator for the ArrayList.
  • hasNext(): Performs a check on the ArrayList to find whether next element is present or not.
  • next(): Accesses the elements of ArrayList

Besides these three methods, we will also use the While loop to iterate the element checking step.

Refer to the illustration below:

Output:

Elements of ArrayList are:
MacOS
Windows
ChromeOS
Linux
Ubuntu

If you don’t want to use While loop in the above program, you can use the for loop.

Print ArrayList in java using ListIterator

You can also use ListIterator rather than Iterator to print ArrayList in java.

With ListIterator, you can traverse in front and back directions.
Let’s see with the help of example:

Output:

Elements of ArrayList are:
Delhi
Mumbai
Paris
Rome
New york
Elements of ArrayList in reverse order are:
New york
Rome
Paris
Mumbai
Delhi

Print ArrayList in java using Stream

You can use Java 8 Stream‘s foreach loop to print ArrayList in java.

Here is an simple example:

Output:

Elements of ArrayList are:
Apple
Banana
Grapes
Orange

Print ArrayList in java using toString()

If you just want to print ArrayList on console, you can directly print it using its reference. It will call toString() method internally of type of ArrayList(String in this example).

Output:

Elements of ArrayList are:[Apple, Banana, Grapes, Orange]

Print ArrayList of custom objects

If you have custom object in ArrayList, then you may need to implement toString() method in the custom object to print ArrayList properly.

Let’s see with the help of example:
Create a class named Student with name and age attributes.

Create main class PrintArrayListStudentMain.java which we will use to print the ArrayList

Output:

If you notice the output, it is printing unreadble String because we did not implement toString() method in Student class.

Let’s implement toString() method in Student class.

Now, run PrintArrayListStudentMain.java again and you will get below output:

Student List:[Student{name=’John’, age=12}, Student{name=’Martin’, age=11}, Student{name=’Mary’, age=10}, Student{name=’Sneha’, age=13}]

As you can see, we are able to print ArrayList in readable format now.

Conclusion

That’s how you print ArrayList elements using these three different methods quite easily. Apart from these three methods, you can come up with your method, do let us know. If you run into some errors, you can drop down your queries and we will discuss them further.

That’s all about how to print ArrayList in java.


import_contacts

You may also like:

Related Posts

  • Java Set to Array
    12 May

    Java Set to Array

    Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

  • 15 April

    How to Deep Copy Arraylist in Java

    Learn about how to create deep copy of ArrayList in different ways.

  • 02 October

    Initialize ArrayList with values in Java

    Table of ContentsUsing Arrays.asList()Initialize ArrayList with String valuesintialize ArrayList with Integer valuesintialize ArrayList with float valuesUsing Stream in Java 8Using Factory Method in java 9Using double braces In this article, we will learn to initialize ArrayList with values in Java. ArrayList is an implementation class of List interface in Java. It is used to store […]

  • 17 March

    PriorityQueue in Java 8

    Table of ContentsPriority Queue Data StructureSome Important PointsConstructorsMethodsCreating a PriorityQueueUsing No-arg constructor (Natural ordering)Using Custom Comparator In this post, we will see about Java 8 PriorityQueue. When the objects are supposed to be processed on the basis of their priority, in that scenario we use PriorityQueue. It’s a special type of queue (also, unbound queues) […]

  • 06 October

    2d Arraylist java example

    In this post, we will see how to create 2d Arraylist in java. Best way to create 2d Arraylist is to create list of list in java. [crayon-60c76909b7ebf636071492/] Let’s create a program to implement 2d Arraylist java. [crayon-60c76909b7ec6212200214/] Output: 2nd element in list3 : List3_Str2 3nd element in list1 : List1_Str3 1st element in list2 […]

  • 04 May

    How HashMap works in java

    Table of ContentsPutGetKey points to RemeberJava HashMap Most common interview questions are <code>How HashMap works in java</code>, “How get and put method of HashMap work internally”. Here I am trying to explain internal functionality with an easy example. [crayon-60c76909eea57148826346-i/]  is one of the most used Collections in java.Rather than going through theory, we will start […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.