Java ArrayList subList()

The syntax of the subList() method is:

arraylist.subList(int fromIndex, int toIndex)

Here, arraylist is an object of the ArrayList class.


subList() Parameters

The subList() method takes two parameters.

  • fromIndex - the starting position from where elements are extracted
  • toIndex - the ending position up to which elements are extracted

subList() Return Value

  • returns a portion of arraylist from the given arraylist
  • throws IndexOutOfBoundsException, if fromIndex is less than 0 or toIndex is greater than the size of arraylist
  • throws IllegalArgumentException, if fromIndex is greater than toIndex.

Note: The portion of arraylist contains elements starting at fromIndex and extends up to element at toIndex-1. That is, the element at toIndex is not included.

Using ArrayList subList() method to access part of an arraylist
Working of ArrayList subList()

Example 1: Get a Sub List From an ArrayList

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<String> languages = new ArrayList<>();

        // add some elements to the ArrayList
        languages.add("JavaScript");
        languages.add("Java");
        languages.add("Python");
        languages.add("C");
        System.out.println("ArrayList: " + languages);

        // element from 1 to 3
        System.out.println("SubList: " + languages.subList(1, 3));
    }
}

Output

ArrayList: [JavaScript, Java, Python, C]
SubList: [Java, Python]

In the above example, we have used the subList() method to get elements from index 1 to 3 (excluding 3).

Note: If you want to know how to get the index of the specified element, visit Java ArrayList indexOf().


Example 2: Split a Single ArrayList into Two ArrayLists

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<Integer> ages = new ArrayList<>();

        // add some elements to the ArrayList
        ages.add(10);
        ages.add(12);
        ages.add(15);
        ages.add(19);
        ages.add(23);
        ages.add(34);
        System.out.println("List of Age: " + ages);

        // ages below 18
        System.out.println("Ages below 18: " + ages.subList(0, 3));

        // ages above 18
        System.out.println("Ages above 18: " + ages.subList(3, ages.size()));
    }
}

Output

List of Age: [10, 12, 15, 19, 23, 34]
Ages below 18: [10, 12, 15]
Ages above 18: [19, 23, 34]

In the above example, we have created an arraylist named ages. Here, we have used the subList() method to split the arraylist into two arraylists: Ages below 18 and Ages above 18.

Note that we have used the ages.size() method to get the length of the arraylist. To learn more on the size() method, visit Java ArrayList size().

Did you find this article helpful?