Print ArrayList in Java explained with examples

Read Time:8 Minute, 21 Second

Table of Contents

We’ll look at how to print an ArrayList in Java in this tutorial. The Array data structure in Java is highly strong, yet it has its constraints. To get around these limitations, the ArrayList data structure was created.

Before we get started on our topic, let us give you a quick primer on ArrayList.

Introduction to ArrayList

ArrayList is a more advanced variant of Array since it supports resizable arrays. Aside from that, ArrayList is a Java collection that implements the Java List. Further, the ArrayList is the advanced array version, yet it is less efficient in time optimization than basic arrays.

The ArrayList class is additionally built on an Array data structure and implements the List interface. Because of the usefulness and flexibility it provides, it is widely used. Most developers prefer Arraylist to Array because it is a better alternative to regular Java arrays. The ArrayList implementation of the List interface is a resizable-array implementation. Any optional list operations are implemented, and all elements, including null, are allowed.

We kept it straight and short because we weren’t focusing on ArrayList details.

SUGGESTED READ

How to print ArrayList elements in Java

Yes, you read that correctly. ArrayList elements can’t be printed in a single method, fortunately. Even though there are dozens of options, we’ll examine the eight main ones while illustrating using various examples in this guide. To print items, first build a String ArrayList and put data as strings in it, then show them using any of the following methods:

  • For-loop
  • For-each loop
  • Using Iterator
  • Using List-iterator
  • Using Stream
  • using toString()
  • Using Arrays class
  • Using IDs

A string ArrayList is seen below. Using the add() method of the ArrayList, we created a list object and inserted the names of computer companies.

Using for loop

We get the length of the ArrayList using its size() method, up to which we need to retrieve elements to use for the loop. We utilized the ArrayList’s get(i) method to retrieve the data at the ArrayList’s indexes.

Using iterator

Iterators are used to obtain elements in the Java collection framework. The iterator() method of the ArrayList returns an iterator for the list.hasNext() is a method in the Iterator that checks if the next element is available. Iterator’s next() method also returns elements.

To traverse the ArrayList, we constructed a while loop. We use the hasNext() method in the loop to see if the next element is available. The hasNext() method of an iterator returns the Boolean value true or false. If hasNext() returns true, the loop uses the Iterator next() method to get the ArrayList members and prints them using System.out. println method is a printing method. There are no more elements in the list if hasNext() returns false.

SUGGESTED READ

Using for-each loop

The same for loop is expressed differently here, utilizing Java’s for-each loop or advance loop function. This loop retrieves each element from the ArrayList object one at a time.

Using list-iterator

We can also use ListIterator to traverse the ArrayList’s elements. The hasNext() method checks if an element is present, and the next() method retrieves ArrayList entries. ListIterator is identical to the iterator. However, ListIterator is bidirectional, whereas the iterator is unidirectional.

The only difference is that we must first start it with null in the case of a list iterator.

Using Stream in Java to print an ArrayList

To print an ArrayList in Java, you can use the foreach loop in Java 8 Stream.

Using toString() to print ArrayList in java

You can use its reference if you merely want to output ArrayList on the console. Internally, it will use the toString() function of the ArrayList type (String in this example).

SUGGESTED READ

Using Arrays class to print ArrayList Elements in Java

To print the elements of an ArrayList, convert it to an array and use the toString function of the Arrays class.

If you wish to get rid of the square brackets, use the replaceAll approach described below.

Print Arraylist in Java Using IDs

Every ArrayList element has a unique ID that may be obtained by printing the ArrayList without using any methods such as toString (). It will display the raw ArrayList with the item IDs, as shown in the output of the example:

Complete Java code for printing ArrayList Elements in different ways

The following is the complete code for printing all items of the ArrayList using different techniques:

SUGGESTED READ

Let’s say you’ve got three or more ArrayList. Is it necessary for you to rewrite the code to output the Elements? NO, you may establish a single method to print many ArrayList and call it for each ArrayList individually, as seen below.

The code sample below has two array lists: “days” and “fruits.” Both array lists are printed using the single method “printArrayListElements(ArrayList a)”.

Printing an ArrayList of custom objects

If you have a custom object in an ArrayList, you may need to implement the toString() function in that object to correctly display the ArrayList. Let’s have a look at an example:

Create an Employee class with characteristics for name and age.

PrintArrayListEmployeeMain.java is the main class that will be used to print the ArrayList.

SUGGESTED READ

Because the toString() method was not implemented in the Employee class, the output is an unreadable String. Let’s put the toString() function into action in the Employee class.

Now rerun PrintArrayListEmployeeMain.java to get different results. In addition, we can now understandably print ArrayList, as you can see.

Example: Use for loop to Print ArrayList in Java

We are iterating up to the size() of Arraylist in the for loop. We retrieve individual elements using the get() function of the ArrayList in each iteration. Finally, we will output those parts using System.out.println instructions.

Example: Print ArrayList in Java using for-each Loop

The only difference between this procedure and the previous one is that we will use the advanced loop method. So, instead of using the standard for loop, we’ll use its advanced counterpart, which has a few more features. Take a look at the code syntax below:

Although there are only a few minor differences between the two ways described above, they are vastly different in how they work. The full size was retrieved firstly, the index was assessed using that size, and the latter element was accessed. On the other hand, this approach evaluates each ArrayList element serially using a String variable.

SUGGESTED READ

Example: Print Arraylist in Java Using forEach

Every ArrayList in Java provides a forEach method, which, like the for loop, is one of the simplest ways to cycle through all of the objects. We can easily retrieve the names from ModelClass using the getName() method, just like in the previous example.

Example: Print ArrayList in Java using iterator framework

To print the ArrayList element so far, we’ve utilized simple loop principles, but in this method, we’ll use Iterators, which are part of the Java collection architecture. The following Interactors method will be used in this manner.

  • Iterator() is a method that returns an ArrayList iterator.
  • hasNext(): Checks the ArrayList for the presence or absence of the next element.
  • next(): Accesses the ArrayList’s elements.

We’ll iterate the element checking step using the While loop and these three methods.

Take a look at the code snippet below:

Example: Print ArrayList in Java using ListIterator

To print an ArrayList in Java, you can use ListIterator instead of Iterator. You may travel in both front and back directions with ListIterator. Let’s have a look at an example:

SUGGESTED READ

Example: Print Arraylist in Java Using the toString() Command

The last function in this list is an override of the ModelClass’s toString() method. When we use arrModel to call this method, it will return the name. Keep in mind that, as the name implies, this procedure can only return string values.

Example: How to print ArrayList containing custom objects?

How can we print an ArrayList of custom class objects? Consider the following code, which contains an ArrayList of Employee class objects.

Rather than printing the contents of the Employee objects, our code printed their memory addresses. Because the Employee class does not override the toString method, the Object class’s default toString method is used, which prints the object’s address position. Instead of memory locations, let’s override the toString function in the Employee class to get the contents of the Employee object.

Conclusion

ArrayLists have been a hot topic in Java recently. They have a lot more advantages than ordinary arrays. ArrayLists allow you to store multiple objects in a row and delete them when they are no longer needed. They also assist you in doing standard list operations such as sorting and searching. Using a regular array would require you to create your logic for these operations, which would take more time and effort.

ArrayLists are helpful in various situations due to their broad list of advantages. On the other hand, printing is a critical activity that ArrayLists lack. ArrayLists can be made out of basic data kinds (integers and strings) or more complex data types (custom classes). Each of these scenarios necessitates a separate set of actions for printing an ArrayList.

SUGGESTED READ

That’s how you can quickly print ArrayList elements with these methods. Further, you can come up with a method other than these methods; please let us know how the latter goes for you. If you encounter any problems, please submit your questions, and we will look into them further.

Source: https://www.codeunderscored.com/print-arraylist-in-java-explained-with-examples/