Java ArrayList subList()

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

1. ArrayList.subList() API

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

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

The method arguments are:

  • 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 the sublist will also be reflected on the original arraylist.

2. Sublist Between Specified Indices

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

Please note that the arraylist index starts from 0.

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
 
ArrayList<Integer> sublist = list.subList(2, 6);
 
System.out.println(sublist);

Program output.

[2, 3, 4, 5]

3. Sublist From Specified Index to End of List

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

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 A Sublist from the Original List

When we have a sublist view of the arraylist, we can use this sublist to remove multiple items from the arraylist also, as the changes are reflected in both lists.

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: ArrayList Java Docs

Sourcecode on Github

Comments

Subscribe
Notify of
guest
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

Dark Mode

Dark Mode