Print ArrayList in Java

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.

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.

ArrayList arrProgrammingLanguages=new ArrayList();
arrProgrammingLanguages.add("Google");
arrProgrammingLanguages.add("Microsoft");
arrProgrammingLanguages.add("Yahoo");
arrProgrammingLanguages.add("Amazon");
arrProgrammingLanguages.add("Uber");
arrProgrammingLanguages.add("Twitter");
arrProgrammingLanguages.add("Meta");

Using for loop

//using for loop

System.out.println("Using For Loop\n ");
for (int i = 0; i < arrProgrammingLanguages.size();i++)
{ 		      
  System.out.println(arrProgrammingLanguages.get(i)); 		
}   

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

//using iterator
System.out.println("\nUsing the Iterator");
Iterator iterator=arrProgrammingLanguages .iterator();
while(iterator .hasNext())
{
  String obj = iterator.next();
  System.out.println(obj);
}

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.

Using for-each loop

//using for-each loop
System.out.println("\nUsing for-each loop\n");		
for (String strVar : arrProgrammingLanguages)
{ 		      
  System.out.println(strVar); 		
}

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

//Using list iterator
litrVar=arrProgrammingLanguages.listIterator();

System.out.println("\n Using the list iterator");
while(litrVar.hasNext()){
  System.out.println(litrVar.next());
}

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.

ListIterator<String> litrVar = null;

Using Stream in Java to print an ArrayList

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

package org.under.codeunderscored;
 
import java.util.ArrayList;
 
public class PrintArrayListMain {
 
    public static void main(String args[])
    {
        ArrayList<String> codingList = new ArrayList<>();
 
        fruitList.add("Java");
        fruitList.add("Python");
        fruitList.add("JavaScript");
        fruitList.add("GO");
        System.out.println("Elements of  the given ArrayList are:");
 
        codingList.stream().forEach(System.out::println);
 
    }
}

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).

package org.under.codeunderscored;
 
import java.util.ArrayList;
 
public class PrintArrayListMain {
 
    public static void main(String args[])
    {
        ArrayList<String> codingList = new ArrayList<>();
 
        codingList.add("Python");
        codingList.add("Java");
        codingList.add("JavaScript");
        codingList.add("Go");
        System.out.println("Elements of the ArrayList include:"+codingList);
    }
}

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.

System.out.println("Print the Arraylist using the Arrays.toString method");
System.out.println( The Arrays.toString(aListDays.toArray()) );

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

System.out.println(Arrays.toString(aListDays.toArray()) .replaceAll("[\\[\\]]", "") );

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:

import java.util.ArrayList;

public class Codeunderscored {

    public static void main(String[] args) {

        ArrayList<ModelClass> modelList;

        ModelClass modelOne = new ModelClass();
        ModelClass modelTwo = new ModelClass();
        ModelClass modelThree = new ModelClass();

        modelOne.setName("Joy");
        modelTwo.setName("Ann");
        modelThree.setName("Mike");

        modelList = new ArrayList<ModelClass>();
        modelList.add(modelOne);
        modelList.add(modelTwo);
        modelList.add(modelThree);

        System.out.println(modelList);

    }
}

class ModelClass{

    String name;
    void setName(String name){
        this.name = name;
    }

}

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:

import java.util.*;
import java.util.ArrayList;
import java.util.Iterator;

public class Codeunderscored {

	public static void main(String[] args) {
	
		 ListIterator litrVar = null;
		ArrayList arrMonths=new ArrayList();
		arrMonths.add("January");
		arrMonths.add("February");
		arrMonths.add("March");
		arrMonths.add("April");
		arrMonths.add("May");
		arrMonths.add("June");
		arrMonths.add("July");
		
		//using for loop
		System.out.println("Using the For Loop\n ");
	      for (int i = 0; i < arrMonths.size();i++)
	      { 		      
	          System.out.println(arrMonths .get(i)); 		
	      }   		
		
		//using for-each loop
	      System.out.println("\nUsing for-each loop\n");		
	      for (String strVar : arrMonths)
	      { 		      
	           System.out.println(strVar); 		
	      }

	      //using iterator
	      System.out.println("\nUsing Iterator");
	      Iterator itrVar=arrMonths .iterator();
	      while(itrVar.hasNext())
	        {
	          String objVar = itrVar.next();
	          System.out.println(objVar);
	        }
	    //Using list iterator
	      litrVar=arrMonths .listIterator();
	   
	      System.out.println("\n Using the given list iterator");
	      while(litrVar.hasNext()){
	         System.out.println(litrVar.next());
	      }
	      
	}

}

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)”.

import java.util.ArrayList;
public class Codeunderscored {

	public static void main(String[] args) {

		ArrayList citiesArr = new ArrayList();
		citiesArr.add("New York");
		citiesArr.add("London");
		citiesArr.add("Paris");
		citiesArr.add("Tokyo");
		citiesArr.add("Nairobi");
		citiesArr.add("Armsterdam");
		citiesArr.add("Zurich");

		System.out.println("Cities Array List:");
		printArrayListElements(citiesArr);

		ArrayList compCompanies = new ArrayList();
		compCompanies.add("Amazon");
		compCompanies.add("Apple");
		compCompanies.add("Alibaba");

		System.out.println("Computer Companies Array List:");
		// print computer companies array list
		printArrayListElements(compCompanies);

	}

	public static void printArrayListElements(ArrayList a) {
		for (int i = 0; i < a.size(); i++) {
			System.out.println(a.get(i));
		}
	}
}

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.

package org.under.codeunderscored;
 
public class Employee {
    String name;
    int age;
 
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}

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

package org.arpit.codeunderscored;
 
import java.util.ArrayList;
 
public class PrintArrayListEmployeeMain {
 
    public static void main(String[] args) {
        ArrayList<Employee> employeesList=new ArrayList<>();
 
        Employee empOne=new Employee("Mike",52);
        Employee empTwo=new Employee("Ann",31);
        Employee empThree=new Employee("Joy",20);
        Employee empFour=new Employee("Moses",11);
 
        employeesList.add(empOne);
        employeesList.add(empTwo);
        employeesList.add(empThree);
        employeesList.add(empFour);
 
        System.out.println("Employees List:"+employeesList);
    }
}

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.

package org.under.codeunderscored.entry;
 
public class Employee {
    String name;
    int age;
 
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

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.

package org.under.codeunderscored;
 
import java.util.ArrayList;
 
public class PrintArrayListMain {
 
    public static void main(String[] args) {
        ArrayList<String> arrCars = new ArrayList<>();
 
        arrCars.add("Mercedes Benz");
        arrCars.add("Rolls Royce");
        arrCars.add("Tesla");
        arrCars.add("Ferrari");
 
        System.out.println("Elements of the ArrayList are:");
        for (int i = 0; i < arrCars.size(); i++) {
            System.out.println(arl.get(i) + " ");
        }
    }
}

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:

package org.under.codeunderscored;
 
import java.util.ArrayList;
 
public class PrintArrayListMain {
 
    public static void main(String[] args) {
        ArrayList<String> arrayCountries = new ArrayList<>();
 
        arrayCountries.add("Canada");
        arrayCountries.add("Australia");
        arrayCountries.add("Russia");
        arrayCountries.add("Norway");
 
        System.out.println("Countries in the ArrayList are:");
        for (String country : arrayCountries) {
            System.out.println(country);
        }
    }
}

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.

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.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Consumer;


public class Codeunderscored {
    public static void main(String[] args) {

        ArrayList<ModelClass> arrModel;

        ModelClass modelOne = new ModelClass();
        ModelClass modelTwo = new ModelClass();
        ModelClass modelThree = new ModelClass();

        modelOne.setName("Joy");
        modelTwo.setName("Thomas");
        modelThree.setName("Mike");

        arrModel = new ArrayList<ModelClass>();
        arrModel.add(modelOne);
        arrModel.add(modelTwo);
        arrModel.add(modelThree);

        arrModel.forEach(new Consumer<ModelClass>() {
            @Override
            public void accept(ModelClass modelClass) {
                System.out.println(modelClass.getName());
            }
        });

    }
}

class ModelClass{

   private String name;
    void setName(String name){
        this.name = name;
    }

    String getName(){
        return name;
    }

}

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:

package org.under.codeunderscored;
 
import java.util.ArrayList;
import java.util.Iterator;
 
public class PrintArrayListMain {
 
    public static void main(String args[])
    {
        ArrayList<String> arrOperatingSystem = new ArrayList<>();
 
        arrOperatingSystem.add("MacOS");
        arrOperatingSystem.add("Windows");
        arrOperatingSystem.add("ChromeOS");
        arrOperatingSystem.add("Linux");
        arrOperatingSystem.add("Ubuntu");
 
        System.out.println("Elements in the ArrayList are:");
        Iterator<String> arrIterator = arList.iterator();
        while(arrIterator .hasNext())
        {
            String item = arrIterator.next();
            System.out.println(item);
        }
    }
}

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:

package org.under.codeunderscored;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
 
public class PrintArrayListMain {
 
    public static void main(String args[])
    {
        ArrayList<String> arrClubs = new ArrayList<>();
 
        arrClubs.add("Chelsea");
        arrClubs.add("Liverpool");
        arrClubs.add("Manchester");
        arrClubs.add("Newcastle");
        arrClubs.add("Brighton");
 
        System.out.println("Clubs in the ArrayList are:");
        ListIterator<String> listIterator = arrClubs.listIterator();
        while(listIterator .hasNext())
        {
            String item = listIterator.next();
            System.out.println(item);
        }
 
        System.out.println("Clubs of ArrayList in reverse order are:");
        ListIterator<String> listItrVar = citiesList.listIterator(arrClubs.size());
        while(listItrVar.hasPrevious())
        {
            String item = listItrVar.previous();
            System.out.println(item);
        }
    }
}

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.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Consumer;


public class Codeunderscored {
    public static void main(String[] args) {

        ArrayList<ModelClass> arrModel;

        ModelClass modelOne = new ModelClass();
        ModelClass modelTwo = new ModelClass();
        ModelClass modelThree = new ModelClass();

        modelOne.setName("Joy");
        modelTwo.setName("Mike");
        modelThree.setName("James");

        arrModel = new ArrayList<ModelClass>();
        arrModel.add(modelOne);
        arrModel.add(modelTwo);
        arrModel.add(modelThree);

        System.out.println(arrModel .toString());

    }
}

class ModelClass{

   private String name;
    void setName(String name){
        this.name = name;
    }


    @Override
    public String toString() {
        return "ModelClass{" +
                "name='" + name + '\'' +
                '}';
    }
}

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.

package com.javacodeexamples.collections.arraylist;
 
import java.util.ArrayList;
 
public class JavaPrintArrayList {
 
    public static void main(String[] args) {
        
        ArrayList<Employee> arrEmployee = new ArrayList<Employee>();
        arrEmployee.add( new Employee("Kane", "Brown") );
        arrEmployee.add( new Employee("Ann", "Faith") );
        arrEmployee.add( new Employee("Moses", "Sang") );
        
        for( Employee emp : arrEmployee)
            System.out.println(emp);
        
    }
}
 
class Employee{
    
    private String firstName;
    private String lastName;
    
    public Employee(){}
    
    public Employee(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
}

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.

package com.javacodeexamples.collections.arraylist;
 
import java.util.ArrayList;
 
public class JavaPrintArrayListExample {
 
    public static void main(String[] args) {
        
        ArrayList<Employee> arrEmployee = new ArrayList<Employee>();
        arrEmployee.add( new Employee("Kane", "Brown") );
        arrEmployee.add( new Employee("Ann", "Faith") );
        arrEmployee.add( new Employee("Moses", "Sang") );
        
        for( Employee p : arrEmployee)
            System.out.println(p);
        
    }
}
 
class Employee{
    
    private String firstName;
    private String lastName;
    
    public Employee(){}
    
    public Employee(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    public String toString(){
        return "[" + firstName + "," + lastName + "]";
    }
    
}

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.

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.

Similar Posts

Leave a Reply

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