What is ArrayList.subList in Java?
The ArrayList.subList method returns a view/portion of the original list between fromIndex (included) and toIndex (not included).
Syntax
arrayListObj.subList(int fromIndex, int toIndex);
-
fromIndex: Index from which the sublist starts. IffromIndexis less than0, then IndexOutOfBoundsException will be thrown. If thefromIndexis greater thantoIndex, then IllegalArgumentException will be thrown. -
toIndex: Index at which the sublist ends. The element at theendIndexwill not be considered. IftoIndexis greater thanArrayList sizethen, IndexOutOfBoundsException will be thrown. -
The
subListmethod returns a portion of theArrayListobject as aListobject.
import java.util.ArrayList;import java.util.List;class GetSubList {public static void main(String[] args) {ArrayList<String> strList = new ArrayList<>();strList.add("E");strList.add("D");strList.add("U");strList.add("C");strList.add("T");strList.add("I");strList.add("V");strList.add("E");System.out.println("The list is " + strList);List<String> strListCopy = strList.subList(0, strList.size()); // returns complete listSystem.out.println("\nGetting complete list by calling strList.sublist(0, strList.size()) \n" + strListCopy);List<String> firstThreeStr = strList.subList(0, 3);System.out.println("\nGetting first 3 letters of the list by calling strList.sublist(0, 3) \n" + firstThreeStr ); // returns first 3 elements of the list}}
In the code above, we have created a strList ArrayList with some elements.
First, we set the fromIndex as 0 and toIndex as the size of the list to get the complete list. The subList will return a list of elements from index 0 to the index list size -1.
strList.subList(0, strList.size())
Then, we get the first three elements of the strList by calling:
strList.subList(0, 3);
This will extract elements from index 0 to (3 - 1) . Therefore, the elements at index 0, 1, and 2 will be returned.