mydomain
No ADS
No ADS

Java List Tutorial with Examples

  1. List
  2. Examples
  3. listInterator()
  4. stream()
  5. subList(int,int)
  6. spliterator()
  7. toArray(..)
  8. sort(Comparator)
  9. replaceAll(UnaryOperator)

1. List

List is an interface in Java Collection Framework. As it is a subinterface of Collection, it has all the features of a Collection. In addition, it provides a foundation to maintain an ordered Collection. It includes methods allowing inserting, updating, removing, and searching for an element by index. List allows duplicate elements and null elements.
public interface List<E> extends Collection<E>
The hierarchy of classes implements the List interface:
LinkedList is a special class, belonging to both List group and Queue group:
java.util.List
List provides listlterator() method that returns a Listlterator object allowing iteration through elements in forward or backward direction. Classes implementing the List interface are ArrayList, LinkedList, Stack and Vector. Among those, ArrayList and LinkedList are used more widely.
The methods that are defined in List:
List interface
public interface List<E> extends Collection<E> {
  boolean isEmpty();
  boolean contains(Object o);

  Object[] toArray();
  <T> T[] toArray(T[] a);

  boolean containsAll(Collection<?> c);
  boolean addAll(Collection<? extends E> c);
  boolean addAll(int index, Collection<? extends E> c);
  boolean removeAll(Collection<?> c);
  boolean retainAll(Collection<?> c);

  int size();
  boolean equals(Object o);
  int hashCode();

  E get(int index);  
  E set(int index, E element);  
  boolean add(E e);
  void add(int index, E element);
  E remove(int index);
  boolean remove(Object o);
  void clear();

  int indexOf(Object o);
  int lastIndexOf(Object o);

  Iterator<E> iterator();
  ListIterator<E> listIterator();  
  ListIterator<E> listIterator(int index);

  List<E> subList(int fromIndex, int toIndex);

  default Spliterator<E> spliterator()  
  default void replaceAll(UnaryOperator<E> operator)
  default void sort(Comparator<? super E> c)  

  static <E> List<E> of()  
  static <E> List<E> of(E e1)  
  static <E> List<E> of(E e1, E e2)  
  static <E> List<E> of(E e1, E e2, E e3)  
  static <E> List<E> of(E e1, E e2, E e3, E e4)  
  static <E> List<E> of(E e1, E e2, E e3, E e4, E e5)  
  static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6)  
  static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)  
  static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)  
  static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)  
  static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)  

  static <E> List<E> of(E... elements)  
  static <E> List<E> copyOf(Collection<? extends E> coll)  
}

2. Examples

No ADS
List is an interface, so to create a List object you need to create through a class that implements it, such as ArrayList, LinkedList, ..
ListEx1.java
package org.o7planning.list.ex;

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

public class ListEx1 {

    public static void main(String[] args) {
        // Create a List
        List<String> list = new ArrayList<String>();
        
        list.add("One");
        list.add("Three");
        list.add("Four");
        
        // Insert an element at index 1
        list.add(1, "Two");
        
        for(String s: list)  {
            System.out.println(s);
        }
        System.out.println(" ----- ");
        // Remove an element at index 2
        list.remove(2);
        
        for(String s: list)  {
            System.out.println(s);
        }
    }
}
Output:
One
Two
Three
Four
 -----
One
Two
Four
Book.java
package org.o7planning.list.ex;

public class Book {
    private String title;
    private float price;
    
    public Book(String title, float price)  {
        this.title = title;
        this.price = price;
    }
    public String getTitle() {
        return title;
    }

    public float getPrice() {
        return price;
    }  
}
Example: A List object contains Book data types.
ListEx2.java
package org.o7planning.list.ex;

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

public class ListEx2 {

    public static void main(String[] args) {
        Book b1 = new Book("Python Tutorial", 100f);
        Book b2 = new Book("HTML Tutorial", 120f);
        
        // Create an Unmodifiable List
        List<Book> bookList1 = List.of(b1, b2);
        
        // Create a List of Books using ArrayList
        List<Book> bookList = new ArrayList<Book>();
        
        bookList.add(new Book("Java Tutorial", 300f));
        bookList.add(new Book("C# Tutorial", 200f));
        
        // Append all elements to the end of list.
        bookList.addAll(bookList1);
        
        for(Book book: bookList)  {
            System.out.println(book.getTitle() + " / " + book.getPrice());
        }
    }
}
Output:
Java Tutorial / 300.0
C# Tutorial / 200.0
Python Tutorial / 100.0
HTML Tutorial / 120.0
Array -> List
Static method Arrays.asList(..) allows to convert an array into a List object, however, this object has a fixed size, which cannot add or remove existing elements, because it does not support optional methods: add, remove, set and clear.
ListEx3.java
package org.o7planning.list.ex;

import java.util.Arrays;
import java.util.List;

public class ListEx3 {

    public static void main(String[] args) {
        Book b1 = new Book("Python Tutorial", 100f);
        Book b2 = new Book("HTML Tutorial", 120f);
        Book b3 = new Book("Java Tutorial", 300f);
        
        Book[] bookArray = new Book[] {b1, b2, b3};
        
        // Create a Fixed-size List.
        List<Book> bookList = Arrays.asList(bookArray);
        
        for(Book b: bookList)  {
            System.out.println("Book: " + b.getTitle());
        }
    }
}
Output:
Book: Python Tutorial
Book: HTML Tutorial
Book: Java Tutorial

3. listInterator()

No ADS
listlterator() method returns a Listlterator object that allows you to iterate over the elements in forward or backwark direction.
ListIterator<E> listIterator();  

ListIterator<E> listIterator(int index);
Example:
List_listIterator.java
package org.o7planning.list.ex;

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

public class List_listIterator {

    public static void main(String[] args) {
        // Create a List
        List<String> list = new ArrayList<String>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Four");
        
        // Get a ListIterator.
        ListIterator<String> listIterator = list.listIterator();
        
        String first = listIterator.next();
        System.out.println("First:" + first);// -->"One"
       
        String second = listIterator.next();
        System.out.println("Second:" + second);// -->"Two"
       
        if (listIterator.hasPrevious()) {
            System.out.println("Jump back...");
            String value = listIterator.previous();
            System.out.println("Value:" + value);// -->"Two"
        }
 
        System.out.println(" ----- ");
 
        while (listIterator.hasNext()) {
            String value = listIterator.next();
            System.out.println("Value:" + value);
        }
    }
}
Output:
First:One
Second:Two
Jump back...
Value:Two
 -----
Value:Two
Value:Three
Value:Four

4. stream()

List is a subinterface of Collection, therefore it inherits stream() method. Accessing elements of a Collection via Stream makes your code brief and easy to understand:
List_stream.java
package org.o7planning.list.ex;

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

public class List_stream {

    public static void main(String[] args) {
        Book b1 = new Book("Python Tutorial", 100f);
        Book b2 = new Book("HTML Tutorial", 120f);
        
        // Create an Unmodifiable List
        List<Book> bookList1 = List.of(b1, b2);
        
        // Create a List of Books using ArrayList
        List<Book> bookList = new ArrayList<Book>();
        
        bookList.add(new Book("Java Tutorial", 300f));
        bookList.add(new Book("C# Tutorial", 200f));
        
        // Append all elements to the end of list.
        bookList.addAll(bookList1);
        
        // Using Stream
        bookList.stream() //
             .filter(b -> b.getPrice() > 100) // Filter Books with price > 100
             .forEach(b -> System.out.println(b.getTitle() +" / " + b.getPrice()));
    }
}
Output:
Java Tutorial / 300.0
C# Tutorial / 200.0
HTML Tutorial / 120.0

5. subList(int,int)

No ADS
subList(int,int) method returns a partial view of the current List object, including elements from the index fromIndex to tolndex.
"subList" object and the current List object are related. For example, if you remove an element on "subList", that element is also removed from the current List object.
List<E> subList(int fromIndex, int toIndex);
List_subList.java
package org.o7planning.list.ex;

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

public class List_subList {

    public static void main(String[] args) {
        // Create a List
        List<String> originList = new ArrayList<String>();
        
        originList.add("A"); // 0
        originList.add("B"); // 1
        originList.add("C"); // 2
        originList.add("D"); // 3
        originList.add("E"); // 4
        
        List<String> subList = originList.subList(1, 3); // fromIndex .. toIndex
        
        System.out.println("Elements in subList: ");
        for(String s: subList)  {
            System.out.println(s); // B C
        }
        
        subList.clear(); // Remove all elements from subList.
        System.out.println("Elements in original List after removing all elements from subList: ");
        
        for(String s: originList)  {
            System.out.println(s); // B C
        }
    }
}
Output:
Elements in subList:
B
C
Elements in original List after removing all elements from subList:
A
D
E

6. spliterator()

Creates a Spliterator object for traversing and partitioning the List elements.
default Spliterator<E> spliterator()  // Java 8
Spliterator is widely used for traversing and partitioning many different data sources such as Collection (List, Set, Queue), BaseStream, array.
  • Java Spliterator

7. toArray(..)

toArray(..) method returns an array containing all elements of List.
Object[] toArray();

<T> T[] toArray(T[] a);

// Java 11, The default method, inherited from Collection.
default <T> T[] toArray​(IntFunction<T[]> generator)
Example:
List_toArray.java
package org.o7planning.list.ex;

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

public class List_toArray {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("A"); // 0
        list.add("B"); // 1
        list.add("C"); // 2
        list.add("D"); // 3
        list.add("E"); // 4
        
        String[] array = new String[list.size()];
        
        list.toArray(array);
        
        for(String s: array)  {
            System.out.println(s);
        }
    }
}
Output:
A
B
C
D
E

8. sort(Comparator)

No ADS
Default method sort(Comparator) relies on the Comparator object, which is provided to compare the elements in the List and sort their order.
default void sort(Comparator<? super E> c)
Example: A List object contains elements of Book type, we sort them by price and title in ascending order.
List_sort_ex1.java
package org.o7planning.list.ex;

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

public class List_sort_ex1 {

    public static void main(String[] args) {
        Book b1 = new Book("Python Tutorial", 100f);
        Book b2 = new Book("HTML Tutorial", 120f);
        Book b3 = new Book("Java Tutorial", 300f);  
        Book b4 = new Book("Javafx Tutorial", 100f);  
        Book b5 = new Book("CSS Tutorial", 300f);  
        
        List<Book> bookList = new ArrayList<Book>();
        bookList.add(b1);
        bookList.add(b2);
        bookList.add(b3);
        bookList.add(b4);
        bookList.add(b5);
        
        // Sort by ascending price.
        // And Sort by ascending title.
        bookList.sort((book1, book2) -> {
            float a = book1.getPrice() - book2.getPrice();
            if(a > 0)  {
                return 1;
            } else if(a < 0) {
                return -1;
            }
            int b = book1.getTitle().compareTo(book2.getTitle());
            return b;
        });
        
        for(Book b: bookList)  {
            System.out.println(b.getPrice() +" : " + b.getTitle());
        }
    }
}
Output:
100.0 : Javafx Tutorial
100.0 : Python Tutorial
120.0 : HTML Tutorial
300.0 : CSS Tutorial
300.0 : Java Tutorial
The above example uses some new concepts introduced from Java 8 such as Functional interface, Lambda expression. You can read more articles below to get more detailed explanation:

9. replaceAll(UnaryOperator)

No ADS
replaceAll(UnaryOperator) method uses the supplied UnaryOperator parameter to replace each element in the List with a new one.
default void replaceAll(UnaryOperator<E> operator)
Example: A List contains elements of Book type, replacing each of its Book elements with a new Book for a 50% increase in price.
List_replaceAll.java
package org.o7planning.list.ex;

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

public class List_replaceAll {

    public static void main(String[] args) {
        Book b1 = new Book("Python Tutorial", 100f);
        Book b2 = new Book("HTML Tutorial", 120f);
        Book b3 = new Book("Java Tutorial", 300f);  
        Book b4 = new Book("Javafx Tutorial", 100f);  
        Book b5 = new Book("CSS Tutorial", 300f);  
        
        List<Book> bookList = new ArrayList<Book>();
        bookList.add(b1);
        bookList.add(b2);
        bookList.add(b3);
        bookList.add(b4);
        bookList.add(b5);
        
        // Replace Book with new Book with the price increased by 50%.
        bookList.replaceAll(b -> new Book(b.getTitle(), b.getPrice() * 150f/100));
        
        for(Book b: bookList)  {
            System.out.println(b.getPrice() + " : " + b.getTitle());
        }
    }
}
Output:
150.0 : Python Tutorial
180.0 : HTML Tutorial
450.0 : Java Tutorial
150.0 : Javafx Tutorial
450.0 : CSS Tutorial
  • Java UnaryOperator
No ADS
No ADS