top of page
Writer's pictureThe Tech Platform

Exploring Java List: A Complete Guide

When it comes to managing collections of elements in Java, the List interface plays a central role. In this article, we will explore Java List, understand its significance, and learn how it offers dynamic ways to organize and manipulate data. From fundamental concepts to practical implementations, join us on this journey to unlock the potential of List in Java.


Table of Contents:

remove (E element)

get (int index)

size()

isEmpty()

clear()

addAll()

indexOf()

lastIndexOf()

sort()

iterator()


What is a Java List?

A Java List is an ordered collection of objects. It can be used to store a collection of elements that can be accessed by their index. Lists are a versatile data structure that can be used for a variety of tasks, such as storing a shopping list, a list of students in a class, or a list of employees in a company.


There are several reasons why you might use a Java List:

  • Lists are ordered, so you can access elements by their index.

  • Lists can store duplicate elements.

  • Lists allow you to insert and remove elements at any position.

  • Lists are a versatile data structure that can be used for a variety of tasks.


Create a List in Java

Below is a Java program to create a list in Java:

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Print the list
        System.out.println("The Fruit List:");
        System.out.println(list);
    }
}

Output:

Creating Java List

Java List Methods

Below is a compilation of Java List methods:

  1. remove (E element)

  2. get (int index)

  3. size()

  4. isEmpty()

  5. clear()

  6. addAll()

  7. indexOf()

  8. lastIndexOf()

  9. sort()

  10. iterator()


1. remove(E element):

Removes the first occurrence of the specified element from the list.


In Java, there are two ways to remove an element from a list:

  • Using the remove() method with the element to be removed as the argument.

  • Using the remove(int index) method with the index of the element to be removed as the argument.

Consider the below method to remove an element from Java List using remove() method:

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");
        
        
        System.out.println("The original Fruit List:");
        System.out.println(list);    
        
        // Remove the element "Oranges" from the list
        list.remove("Oranges");

        // Print the list
        System.out.println("The Fruit List after removing the element:");
        System.out.println(list);
    }
}

Output:

Remove element from Java List

2. get(int index)

The get(int index) method is a method of the List interface. It is used to get the element at the specified index in the list. The index is an integer that specifies the position of the element in the Java list. The elements in a list are numbered starting from 0.

def get_element(list, index):"
    ""Gets the element at the specified index in the list."""
    
    if index < 0or index >= len(list):     
        raise IndexError("Index is out of range")   
    returnlist[index]   
    
fruits = ["Apple", "Banana", "Oranges", "Grapes", "Watermelon", "Blueberry"]  

# Get the element at the index 0 
first_fruit = get_element(fruits, 0)  
print("The first fruit is:", first_fruit)

In the above code, the get(int index) method is used to get the element at the index 0 of the list list. The list list contains the strings "Apple", "Banana", "Oranges", "Grapes", "Watermelon", and "Blueberry". The index 0 corresponds to the element "Apple". Therefore, the get(int index) method will return the string "Apple".


Here are some additional things about the get(int index) method:

  • The get(int index) method throws an IndexOutOfBoundsException if the index is out of range.

  • The get(int index) method is a constant time operation, which means that it takes the same amount of time to execute regardless of the index of the element being retrieved.


3. size()

The size() method in Java is a method of the List interface. It is used to get the number of elements in the list. The size() method does not take any parameters.

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Get the size of the list
        int size = list.size();
        
        // Print the list
        System.out.println("The Fruit List:");
        System.out.println(list);
        System.out.println("The size of the list is: " + size);
    }
}

Output:

check the size of Java List

Here are some additional things about the size() method in Java List:

  • The size() method is a constant time operation, which means that it takes the same amount of time to execute regardless of the number of elements in the list.

  • The size() method is often used in conjunction with other list methods, such as get(), remove(), and clear().

Consider the below code where we use the size() method in conjunction with the get() method.

def get_size(list):
  """Gets the size of the list."""
  return len(list)


fruits = ["Apple", "Banana", "Oranges", "Grapes", "Watermelon", "Blueberry"]

# Get the size of the list
number_of_fruits = get_size(fruits)

print("The number of fruits is:", number_of_fruits)

In the above code, the get_size() function first uses the len() function to get the length of the list. The len() function is a built-in function in Python that returns the length of an object. In this case, the object is the list fruits.


The get_size() function then returns the length of the list. The number_of_fruits variable is then assigned the value returned by the get_size() function.


Finally, the print() function prints the value of the number_of_fruits variable.


4. isEmpty()

The isEmpty() method in Java is a method of the List interface. It is used to check if the list is empty. The isEmpty() method does not take any parameters.


The isEmpty() method returns a boolean value. The value true is returned if the list is empty, and the value false is returned if the list is not empty.

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Check if the list is empty
        boolean isListEmpty = list.isEmpty();

        System.out.println("Is the list empty? " + isListEmpty);
        System.out.println("The Fruit List:" + list);
     
    }
}

Output:

check whether the Java List is empty or not?

The isEmpty() method is invoked to check if a list is empty. This can be useful in a variety of situations in Java List, such as:

  • Checking if a list has been initialized.

  • Checking if a list has been cleared.

  • Checking if a list has any elements.

  • Determining whether to add an element to a list.

  • Determining whether to remove an element from a list.

The isEmpty() method is a constant time operation, which means that it takes the same amount of time to execute regardless of whether the list is empty or not.


The isEmpty() method is often used in conjunction with other list methods, such as add(), remove(), and clear().


5. clear()

The clear() method in Java is a method of the List interface. It is used to clear the list, removing all of its elements. The clear() method does not take any parameters.


The following code snippet shows how to use the clear() method:

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Clear the list
        list.clear();

        // Print the index
        System.out.println("The Fruit List:");
        System.out.println(list);
    }
}

Output:

clear the Java List

Here are some additional things about the clear() method in Java List:

  • The clear() method is a void method, which means that it does not return any value.

  • The clear() method is often used in conjunction with other list methods, such as add(), remove(), and isEmpty().


6. addAll(Collection<? extends E> c)

The addAll() method in Java is a method of the List interface. It is used to add all of the elements in the specified collection to the list. The addAll() method takes one parameter, which is the collection of elements to be added.

import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collection;

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Create a collection of strings
        Collection<String> fruits = new ArrayList<>();
        fruits.add("Dragon fruit");
        fruits.add("Melon");
        fruits.add("Strawberry");

// Add all the fruits to the list
list.addAll(fruits);


        // Print the index
        System.out.println("The Fruit List:");
        System.out.println(list);
    }
}

Output:

addAll() method in Java List

In the code above, the addAll() method is used to add all of the elements in the collection fruits to the list list. The collection fruits contains the strings "Dragon fuit", "Melon", and "Strawberry". After the addAll() method is called, the list list contains all of the elements from the collection fruits.


Here are some additional things about the addAll() method in Java List:

  • The addAll() method is a boolean method. It returns true if all of the elements in the collection were successfully added to the list, and false if not.

  • The addAll() method throws an NullPointerException if the collection is null.

  • The addAll() method throws a ClassCastException if the elements in the collection are not of the same type as the elements in the list.


7. indexOf(E element)

The indexOf(E element) method in Java is a method of the List interface. It is used to find the index of the first occurrence of the specified element in the list. The indexOf() method takes one parameter, which is the element to be searched for.

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Find the index of the element "Oranges"
        int index = list.IndexOf("Banana");

        // Print the index
        System.out.println("The Fruit List:");
        System.out.println(list);
        System.out.println("The last index of Banana is: " + index);
    }
}

In the code above, the indexOf() method is used to find the index of the element "Banana" in the list list. The element "Banana" is found at the index 1.


Here are some additional things about the indexOf() method in Java List:

  • The indexOf() method returns the index of the first occurrence of the element, or -1 if the element is not found.

  • The indexOf() method throws a NullPointerException if the element is null.


8. lastIndexOf(E element)

The lastIndexOf(E element) method in Java is a method of the List interface. It is used to find the index of the last occurrence of the specified element in the list. The lastIndexOf() method takes one parameter, which is the element to be searched for.

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Find the index of the element "Oranges"
        int index = list.lastIndexOf("Oranges");

        // Print the index
        System.out.println("The Fruit List:");
        System.out.println(list);
        System.out.println("The last index of Oranges is: " + index);
    }
}

Output:

index of the element in Java List

In the code above, the lastIndexOf() method is used to find the index of the last occurrence of the element "Oranges" in the list list. The element "Oranges" is found at the index 2.


Here are some additional things about the lastIndexOf() method in Java List:

  • The lastIndexOf() method returns the index of the last occurrence of the element, or -1 if the element is not found.

  • The lastIndexOf() method throws a NullPointerException if the element is null.


9. sort(Comparator<? super E> c)

The sort(Comparator<? super E> c) method in Java is a method of the List interface. It is used to sort the elements of the list in ascending order according to the comparator. The sort() method takes one parameter, which is the comparator.


The comparator is an object that implements the Comparator interface. The Comparator interface defines the following methods:

  • int compare(Object o1, Object o2): This method compares two objects and returns an integer value. The return value indicates the order of the two objects. A value less than 0 indicates that the first object is less than the second object, a value of 0 indicates that the two objects are equal, and a value greater than 0 indicates that the first object is greater than the second object.

Consider the below code which shows how to use the sort() method in Java list:

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Create a comparator that compares strings in ascending order
        Comparator<String> stringComparator = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        };
        
         System.out.println("The unsorted Fruit List:" + list);
        
        // Sort the list using the comparator
        list.sort(stringComparator);

        // Print the list
        System.out.println("The sorted Fruit List:");
        System.out.println(list);
    }
}

Output:

sort the Java List

In the code above, the sort() method is used to sort the elements of the list list in ascending order according to the comparator stringComparator. The stringComparator comparator compares two strings in ascending order.


Here are some additional things about the sort() method in Java List:

  • The sort() method is a void method, which means that it does not return any value.

  • The sort() method throws a ClassCastException if the elements of the list are not of the same type.


10. iterator()

The iterator() method in Java is a method of the List interface. It is used to create an iterator for the list. The iterator allows you to traverse the elements of the list one by one. The iterator() method does not take any parameters.

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

public class ListDemo {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");
        list.add("Grapes");
        list.add("Watermelon");
        list.add("Blueberry");

        // Create an iterator for the list
        Iterator<String> iterator = list.iterator();

        // Iterate over the list
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
    }
}

Output:

iterate the Java List

In the code above, the iterator() method is used to create an iterator for the list list. The iterator is then used to iterate over the list and print each element to the console.


Here are some additional things about the iterator() method in Java List:

  • The iterator() method returns an iterator for the list.

  • The iterator is an object that implements the Iterator interface.

  • The Iterator interface defines methods for traversing the elements of a collection.


List of Lists

A list of lists in Java is a list that contains other lists. Each of the inner lists can contain any type of object. A list of lists in Java is used to represent a data structure that contains a collection of lists. Each of the inner lists can contain any type of object.


List of lists can be used to represent a variety of data structures, such as:

  • A nested list of objects

  • A table of data

  • A tree structure

  • A graph

To create a list of lists in Java, you can use the ArrayList class. The following code snippet shows how to create a list of lists of strings:

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

public class ListOfLists {

    public static void main(String[] args) {
        // Create a list of lists
        List<List<String>> listOfLists = new ArrayList<>();

        // Add a list of strings to the list of lists
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Oranges");
        listOfLists.add(fruits);

        // Add another list of strings to the list of lists
        List<String> vegetables = new ArrayList<>();
        vegetables.add("Potato");
        vegetables.add("Carrot");
        vegetables.add("Beans");
        listOfLists.add(vegetables);

        // Print the list of lists
        System.out.println("The list of lists:");
        System.out.println(listOfLists);
    }
}

List of lists can be used to store data in a hierarchical manner. This can be useful for organizing data in a way that makes it easier to access and manipulate.


For example, a list of lists can be used to store a table of data. The outer list can represent the rows of the table, and the inner lists can represent the columns of the table. This makes it easy to access a specific row or column of data.


List of lists can also be used to store a tree structure. The outer list can represent the root node of the tree, and the inner lists can represent the child nodes of the root node. This makes it easy to traverse the tree structure and access the nodes of the tree.


List of lists can be used to store a graph. The outer list can represent the vertices of the graph, and the inner lists can represent the edges of the graph. This makes it easy to traverse the graph and access the vertices and edges of the graph.


Generics with Lists

Generics in Java are a way to specify the type of data that can be stored in a collection. This helps to prevent errors and makes code more readable and maintainable.


Lists in Java are a type of collection that can store a collection of objects. When you create a list without using generics, the list can store any type of object. This can be a problem if you want to store a specific type of object in the list. For example, if you want to store a list of integers, you cannot do this if you do not use generics.


To use generics with lists, you need to specify the type of object that the list can store. You can do this by using the <> symbol.


List of Integer

The List class is a generic class. This means that it can store a collection of objects of any type. However, if we want to restrict the type of objects that can be stored in the list, we can use generics.

List<Integer> numbers = new ArrayList<>();

ArrayList of String

You can also use generics with the ArrayList class. The following code creates an ArrayList that can store only strings. The ArrayList class is a concrete implementation of the List interface. This means that it inherits all of the methods of the List interface, including the add() method.

ArrayList<String> strings = new ArrayList<>();

Set of String

Generics can be used with other collection classes in Java, such as Set and Map. The Set class is a collection that does not allow duplicate elements. This means that if we add an element to a set, we cannot add it again.

Set<String> fruits = new HashSet<>();

Concurrent Lists

A concurrent list in Java is a list that allows multiple threads to access it simultaneously without causing any data corruption.


Concurrent lists are implemented using locks or other synchronization mechanisms to ensure that only one thread can access the list at a time. This prevents race conditions, which are errors that can occur when multiple threads try to access the same data at the same time.


There are two main types of concurrent lists in Java:

  • CopyOnWriteArrayList: This list creates a copy of the underlying array whenever an element is added or removed. This ensures that no thread ever sees an inconsistent view of the list.

  • ConcurrentLinkedDeque: This list uses a linked data structure to store its elements. This allows it to be more efficient than the CopyOnWriteArrayList for operations that add or remove elements at the beginning or end of the list.

Consider the below code:

import java.util.concurrent.CopyOnWriteArrayList;

public class ConcurrentListDemo {

    public static void main(String[] args) {
        // Create a concurrent list
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

        // Add elements to the list
        list.add("Apple");
        list.add("Banana");
        list.add("Oranges");

        System.out.println( "The Fruit list is");
        // Iterate over the list
        for (String fruit : list) {
     
            System.out.println(fruit);
        }

        // Add another element to the list
        list.add("Grapes");

        System.out.println( "The Fruit list after adding the item is");
        // Iterate over the list again
        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

Output:

concurrent list in Java List

In the below code, it first creates a CopyOnWriteArrayList object. This is a concurrent list that creates a copy of the underlying array whenever an element is added or removed. This ensures that no thread ever sees an inconsistent view of the list.


The code then adds three elements to the list: "Apple", "Banana", and "Oranges". It then iterates over the list and prints each element to the console. Finally, the code adds another element to the list: "Grapes". It then iterates over the list again and prints each element to the console.


Concurrent lists are used in applications where it is important to avoid data corruption due to concurrent access. For example, concurrent lists are often used in databases and in applications that process large amounts of data.


Here are some of the benefits of using concurrent lists in Java:

  • They can be used to improve the performance of applications that involve concurrent access to data.

  • They can help to prevent data corruption caused by concurrent access to data.

  • They are relatively easy to use.

Here are some of the drawbacks of using concurrent lists in Java:

  • They can be more complex to implement than non-concurrent lists.

  • They can consume more memory than non-concurrent lists.

  • They can be slower than non-concurrent lists for operations that do not involve concurrent access to data.


Conclusion

This article has provided insights into the Java List interface, covering its creation, diverse methods for modifying lists, and exploration of advanced topics like lists of lists, generics with lists, and concurrent list methods. Armed with this knowledge, you're now well-equipped for successful coding endeavors. Happy coding!

Comments


bottom of page