List Interface in Java With Program Example

List interface inherits Collection interface that provides behaviour to store a group of individual objects. It represents group of individual objects as single entity where duplicates are permitted and elements are ordered in the same manner in which they are inserted. It resides within java.util packages.

Screenshot from 2023 07 04 19 23 17

It defines listIterator() method which returns ListIterator object which empowers the implementing classes to able to traverse their collection objects in both directions, forward and backward.

ArrayList,LinkedList, Stack and Vector are the implementing classes of List interface. Vector class is the legacy class in the List hierarchy.

It allows index based element access and also can be used to insert an element using its position in the given list using zero based index.
A list can contain duplicate elements. It defines its own methods that is specifically made for List implementing classes.

Important Notes

1. It is an ordered collection, meaning, elements are stored the manner in which they are inserted. Therefore, it preserves the insertion order.
2. It uses zero based index in order to access, insert and search element in the list
3. It allows duplicate elements
4. It accepts and stores elements of different types

Method of List Interface

Since, it is child interface of Collection, therefore, it has access all of its method. Apart from this, List interface defines its own methods. The methods and explanations are given below

MethodsExplanation
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Classes that implements List interface

These are the following classes that implements List Interface
1. ArrayList
2. LinkedList
3. Vector
4. Stack

ArrayList

ArrayList resembles dynamic array behaviour in Collection framework. It provides a way to overcomes from fixed size problem of standard arrays. Apart from that, it supports several predefined methods and also uses zero-based index to access, remove or retrieve an object from a list. In other words, it is an array list with growable size functionality.

Vector

Vector is a legacy class in Collection framework. Its underlying data structure is also growable array. It uses zero based index in order to operate on objects and its size can be grow or shrink on runtime based on objects in the list.

Stack

Stack is a child class of Vector. As name suggest, its behaviour resembles Stack data structure. It follows basic principle of Stack which is last in first out. Apart from this, it offers various inbuilt methods to perform basic Stack operation, involving, push(), pop() and peak().

LinkedList

LinkedList implements Linked list data structure in Collection framework. It uses addresses to locate and form a sequence of elements that are stored at different location. In this, each element is termed as node which keep data and address of next or previous element.
It can be considered where insertion and deletion, are frequent operation.

How to declare and define a List?

A List interface only declares behaviour, but not implementation. It is not possible to create its object. Therefore, a List can only hold reference of its implementing classes object. Since, it use Generics concept, therefore, it is controllable to define which type of object a list can hold.

Syntax:

List<Obj> listRef = new ArrayList<>();
List<Obj> listRef = new Stack<>();
List<Obj> listRef = new Vector<>();
List<Obj> listRef = new LinkedList<>();

Obj represents the Type of object the list can hold

Below is the simple Java program to declare a list.

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added single element in the list
System.out.println(list); // printing the output
}
}

Output:

[Viewer]

 

Basic Operations that List Interface provides

1. Adding elements to the List

List provides add() and addAll() methods in order to add elements in the list.

Syntax:

add(Object obj) : It adds element to the end of the list
add(int indx,Object obj) : It adds element on specified position
addAll(Collection c) : It adds another list at the end of the list

Below is the simple Java program to add elements in the list

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added single element in the list
list.add("Viewer2"); // added single element in the list
System.out.println(list); // printing the output

list.add(1,"inserted"); // added element at first position
System.out.println(list);

List<String> anotherList = new ArrayList<>();
anotherList.add("another list content1") ;
anotherList.add("another list content2") ;

list.addAll(anotherList); // adding all elements of another list
System.out.println(list);

}
}

Output:

[Viewer, Viewer2]
[Viewer, inserted, Viewer2]
[Viewer, inserted, Viewer2, another list content1, another list content2]

2. Updating elements to the List

List provides set() and replace() method to update the elements of a list.

set(int index, Obj element) : It updates or replaces element in the list at the given position
replaceAll(UniaryOperator op) : It replaces all the elements in the list.

Below is the simple java program to replace elements in the list

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added single element in the list
list.add("Viewer2"); // added single element in the list
System.out.println(list); // printing the output

System.out.println("After replace -----------");
list.set(1, "Kui"); // replaced the viewer2 value with Kui in the list
System.out.println(list);

System.out.println("After replace All -----------");
list.replaceAll(String::toUpperCase); // a lambda expression (Java 8 feature), that denotes replaces all the elements with its Uppercase version
System.out.println(list); // replaced the viewer2 value with Kui in the list

}
}

Output:

[Viewer, Viewer2]
After replace -----------
[Viewer, Kui]
After replace All -----------
[VIEWER, KUI]

3. Deleting elements to the List

List interface provides remove() and removeAll method to delete elements from the list.

remove(int indx) : It deletes elements at the given position
remove(Object obj) : It deletes very first occurrence of the given object
removeAll(Collection c) : It deletes all the eleemnts that matches with the given collection object

Below is the simple Java program to delete or remove elements from a list

Program:

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

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added element in the list
list.add("Viewer2");
list.add("Viewer3");
list.add("Viewer4");
list.add("Viewer3");


System.out.println(list); // printing the output

System.out.println("After deleting element at 1st index -----------");
list.remove(1); // removed the viewer2 value
System.out.println(list);

System.out.println("After deleting element at Viewer3 object (very first match only)-----------");
list.remove("Viewer3"); // removed the viewer3 value,only very first occurrence
System.out.println(list);

System.out.println("After deleting elements defined in another list -----------");
List<String> deleteList = new ArrayList<>();
deleteList.add("Viewer4");
list.removeAll(deleteList); // removed the viewer4 value
System.out.println(list);
}
}

Output:

[Viewer, Viewer2, Viewer3, Viewer4, Viewer3]
After deleting element at 1st index -----------
[Viewer, Viewer3, Viewer4, Viewer3]
After deleting element at Viewer3 object (very first match only)-----------
[Viewer, Viewer4, Viewer3]
After deleting elements defined in another list -----------
[Viewer, Viewer3]

4. Sorting elements in the List

List provides sort() method to sort list

sort (Comparator c) : It sorts list based on given comparator

Below is the simple Java program to sort list

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Sandeep"); // added element in the list
list.add("Sachin");
list.add("Jay");
list.add("Shiva");
list.add("Kui");

System.out.println("Before sorting based on the string length or size"); // printing the output
System.out.println(list); // printing the output

System.out.println("After sorting based on the string length or size"); // printing the output

list.sort(Comparator.comparingInt(String::length)); // It would sort the list based on the size or length of a string in increasing order

System.out.println(list); // printing the output


}
}

Output:

Before sorting based on the string length or size
[Sandeep, Sachin, Jay, Shiva, Kui]
After sorting based on the string length or size
[Jay, Kui, Shiva, Sachin, Sandeep]

5. Iterating over elements in List

List indirectly extends Iterable interface that provides method to iterate through collection objects. iterator() method and forEach() methods are one of methods.

Also, using advance for-each, one can iterate through a list.

Below is the simple Java Program to iterate through a List

Program:

public class ListDeclarationExample {

    public static void main(String[] args) {
        ArrayList<Integer> integerArrayList = new ArrayList<>();
        integerArrayList.add(5);
        integerArrayList.add(10);
        integerArrayList.add(1);

        System.out.println(" Iterating through iterator :: ");
        Iterator itr = integerArrayList.iterator();  // getting iterator object from arraylist instance
        while(itr.hasNext())    // while the list has the content, do
        {
            System.out.println(itr.next()); // returns the current element and moves the iteration state to next element
        }

        System.out.println(" Iterating through forEach :: ");
        integerArrayList.forEach(System.out::println);  // Java 8 forEach with lambda exp
    }
}

Output:

 Iterating through iterator :: 
5
10
1
 Iterating through forEach :: 
5
10
1

 

Leave a Reply