Java List

The List interface is part of the Java Collections Framework and extends the Collection interface. It is an ordered collection (sequence) that allows duplicate elements.The List interface provides methods to add, remove, and access elements by index. The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector.

Here are some key points about the List interface in Java:

  1. Ordered Collection: A List maintains the order in which elements are inserted. Iterating over a List will return the elements in the order they were added.
  2. Allows Duplicates: Unlike Set, a List allows duplicate elements. Each element in a List has its own index.
  3. Indexed Access: Elements in a List can be accessed using their index. The index starts from 0 for the first element and goes up to size() - 1 for the last element.
  4. Dynamic Size: The size of a List can change dynamically as elements are added or removed.

Declaration of Java List Interface

public interface List<E> extends Collection<E> ;

How to Create List :

Creating an instance of the List interface directly is not possible because the List interface is just an interface and cannot be instantiated on its own. You can create an instance of a class that implements the List interface such using ArrayList, LinkedList, Vector, Stack.

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

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

Example Of Java List

1. Adding Elements:

List interface in Java provides several add methods to insert elements into the list at different positions. Here’s an explanation of some commonly used add methods:

  1. add(E element): Adds the specified element to the end of the list.
  2. add(int index, E element): Inserts the specified element at the specified position in the list. Shifts the element currently at that position (if any) and any subsequent elements to the right
  3. addAll(int index, Collection<? extends E> c) : Inserts all of the elements in the specified collection into the list, starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right.
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> l1 = new ArrayList<String>(); 
        l1.add(0, "apple");
        l1.add(0, "banana"); 
        l1.add(0, "orange"); 

        System.out.println(l1); // [orange, banana, apple]

        List<String> l2 = new ArrayList<String>(); 
        l2.add("grape");
        l2.add("kiwi");
        l2.add("pineapple");
        System.out.println(l2); // [grape, kiwi, pineapple]

        l2.addAll(0, l1);  
        System.out.println(l2); // [orange, banana, apple, grape, kiwi, pineapple]
    }
}

Here is the Output of above Program

[orange, banana, apple]
[grape, kiwi, pineapple]
[orange, banana, apple, grape, kiwi, pineapple]

In this program when adding elements in the l1 list at the 0th index it will not override the value it shifts value if any is present on that index. When you add an element in l2 using the add function without specifying index It adds the specified element to the end of the list. if adding value using addAll it will add l1 values in 0 index other values will shifted

2. remove element using remove() function

the List interface provides several remove methods to remove elements from a list. Here are some common ones along with examples:

1. remove(int index):

Removes the element at the specified index from the list.

        List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "orange"));
        fruits.remove(1); // Removes element at index 1 (banana)
      System.out.println(fruits);//[apple, orange]
2. remove(Object o):

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

List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "orange","banana"));
fruits.remove("banana"); // Removes the first occurrence of "banana"
System.out.println(fruits);//[apple, orange, banana]
3. removeAll(Collection<?> c):

Removes all elements from the list that are present in the specified collection.

List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "orange"));
List<String> toRemove = Arrays.asList("banana", "orange");
fruits.removeAll(toRemove); // Removes all occurrences of "banana" and "orange"

System.out.println(fruits);//[apple]

3. replace element using set method:

It Replaces the element at the specified index with a new value., Let’s take an example

List<String> fruits = new ArrayList<>(List.of("apple", "banana", "orange"));


// Replace the element at index 1 with a new value
fruits.set(1, "grape");

System.out.println(fruits); // Output: [apple, grape, orange]

4. Get element from List using get function

you can use the get method, which retrieves the element at a specified index. Here’s an example:

List<String> fruits = new ArrayList<>(List.of("apple", "banana", "orange"));

// Get the element at index 1
String secondFruit = fruits.get(1);

System.out.println("Second fruit: " + secondFruit); // Output: Second fruit: banana

5. Iterating over List

Here are various ways to iterate over a List in Java.

1. Using enhanced for-loop (for-each):

The enhanced for-loop simplifies the syntax for iterating over elements in a collection,It’s suitable for simple iterations without the need for index tracking.

List<String> fruits = Arrays.asList("apple", "banana", "orange");
for (String fruit : fruits) {
    // Output: apple, banana, orange
    System.out.println(fruit);
}
2. Using traditional for-loop:

The traditional for-loop with index-based access is useful when you need to know the index of the current element or when modifying elements during iteration.

List<String> fruits = Arrays.asList("apple", "banana", "orange");
for (int i = 0; i < fruits.size(); i++) {
    // Output: apple, banana, orange
    System.out.println(fruits.get(i));
}
3. Using forEach (Java 8 and later):

The forEach method introduced in Java 8 simplifies the code for iterating over elements, especially when combined with lambda expressions. It supports parallel processing for streams.

List<String> fruits = Arrays.asList("apple", "banana", "orange");
fruits.forEach(fruit -> {
    // Output: apple, banana, orange
    System.out.println(fruit);
});

Leave a Reply