Java List subList() Tutorial

In this section, we will learn what the List subList() method is and how to use it in Java.

What is Java List subList() Method?

The Java List subList() method is used to create a view of part of the elements of a list object.

Basically, using this method, we’re creating a sub-list of the elements in a list object, but this sub-list is a live view of the elements of the target list object.

This means if in the main list object, we’ve changed one of the elements that the sub-list also has a reference of, this change will be visible in the sub-list object as well.

Java List subList() Method Syntax:

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

subList() Method Parameters:

This method takes two arguments:

  • The first argument is the index number from which we want to extract a sub-list. The first argument is inclusive.
  • The second argument is the index number where we want the extraction to stop. This second argument is exclusive.

subList() Method Return Value:

The return value of this method is a reference to the sub-list that was created as a result of calling this method.

subList() Method Exceptions:

This method can throw one exception and that is:

IndexOutOfBoundsException: You’ll get this exception if one of the index numbers that we set as the argument of the method is out of the range in the target list object.

Example: using List subList() method

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

public class Main {

    public static void main(String[] args){
        List<String> list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Six");
        list.add("Four");
        list.add("Five");
        list.add("Six");

        List <String> liveView = list.subList(0, 5);

        liveView.remove(0);

        for (String s : list){
         System.out.println(s);
        }
    }
}

Output:

Two

Three

Six

Four

Five

Six

In this example, we’ve created a live view of the list object and stored the reference in the `liveView` variable.

Now, because this reference is a live view of the main list object, we could use the `liveView` variable to access the first element of the main list and remove it.

As a result, when we’ve called the for-each loop to get the elements of the main list object, its first element is removed.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies