How To Use Lists in Java

Collections

By Mayuri Fakirpure

Updated on Feb 12, 2024

This is chapter, we'll explain how to use Lists in Java. Lists are a core part of the Java Collections Framework. Lists allow us to store and manipulate collections of objects that can be accessed by an index. 

We can implement List interface in multiple ways like ArrayList, LinkedList, and Vector. A class which implements this interface must provide implementation add(), clear(), contains(), indexof(), remove() methods.

Let's discuss about basic guide on how to use lists in Java using ArrayList.

Import the ArrayList class

We need to import the ArrayList class before we can use it in our Java code:

import java.util.ArrayList;
import java.util.List; // Optionally, import the List interface

Create an ArrayList

To create an ArrayList, we can simply create a object using new keyword.

List<String> myList = new ArrayList<>();

Add Elements to the List

We can add elements to the ArrayList using the add() method. Here we are adding three elements:

myList.add("Java");
myList.add("Python");
myList.add("C++");

Access Elements

Now, let's access the ArrayList element using get() method and providing the index. Here we are access index 0 element:

String firstElement = myList.get(0); // Accesses the first element ("Java")

Iterate Through the List

We can iterate through the elements of the ArrayList using loops. We can use for or while loop:

// Enhanced for loop
for (String element : myList) {
    System.out.println(element);
}

// Using an Iterator
Iterator<String> iterator = myList.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    System.out.println(element);
}

Remove Elements

If we want to remove specific value from the ArrayList, we can use remove() method. We can mention the value of the element:

myList.remove("C++"); // Removes the element "C++"

Example Code

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> myList = new ArrayList<>();
        
        myList.add("Java");
        myList.add("Python");
        myList.add("C++");
        
        for (String element : myList) {
            System.out.println(element);
        }
    }
}

This is the basic overview of how to use lists in Java. It's depending on your requirements, you can choose different list implementations provided by the Java Collection Framework.

This chapter is completed.