Get sublist of ArrayList – ArrayList subList() method

Learn how to get a sublist of an existing ArrayList. We will be using ArrayList.subList() method to get the sublist of arraylist object.

1. ArrayList.subList() method

This method returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive).

1.1. subList() Method Syntax

public List<E> subList(int fromIndex, int toIndex) 
{
    subListRangeCheck(fromIndex, toIndex, size);
    return new SubList(this, 0, fromIndex, toIndex);
}

1.2. subList() Method Parameters

fromIndex – start index in existing arraylist. It is inclusive.
toIndex – last index in existing arraylist. It is exclusive.

Please note that any change made on objects in sublist will be reflected on original arraylist as well.

2. Get sublist of arraylist example

Java program to get a sublist of arraylist from an existing sublist. We are getting the sublist from index 2 to 6.

Please note that arraylist index starts from 0.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
        
        ArrayList<Integer> sublist = new ArrayList<Integer>( list.subList(2, 6) );
        
        System.out.println(sublist);
    }
}

Program output.

[2, 3, 4, 5]

If we want to get sublist from specified index to end of list, then pass the length of arraylist in second argument of method.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
        
        System.out.println(list.subList(2, list.size()));
    }
}

Program output.

[2, 3, 4, 5, 6, 7, 8, 9]

3. Remove sublist of arraylist example

When we have sublist view of arraylist, we can use this sublist to remove multiple items from arraylist also.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
        
        list.subList(2, 6).clear();
        
        System.out.println(list);
    }
}

Program output.

[0, 1, 6, 7, 8, 9]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial