English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList subList() method extracts a part of the arraylist and returns it.
The syntax of the subList() method is:
arraylist.subList(int fromIndex, int toIndex)
subList() method has two parameters.
fromIndex - The starting position of the element extraction
toIndex - The end position of the element extraction
The subList() method returns a part of the arraylist from the given arraylist.
If fromIndex is less than 0 or toIndex is greater than the size of the arraylist, IndexOutOfBoundsException is thrown
If fromIndex is greater than toIndex, IllegalArgumentException is thrown.
NotefromIndex and extending to the index-1: A part of the arraylist contains elements starting from the index
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create an ArrayList : Get a sublist from the ArrayList // Add some elements to the ArrayList ArrayList<String> languages = new ArrayList<>(); languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); languages.add("C"); + System.out.println("ArrayList: " // languages);1In the above example, we use the subList() method to get a sublist from the index3 elements from + System.out.println("SubList: "1, 3)); } }
Output Result
languages.subList( ArrayList: [JavaScript, Java, Python, C]
SubList: [Java, Python]1In the above example, we use the subList() method to get a sublist from the index3to3) to get the element. (excluding
Note: If you want to know how to get the index of a specified element, please visitJava ArrayList indexOf().
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("Age List: " + ages); //under18years System.out.println("Age is18Below Age: " + ages.subList(0, 3)); //over18years System.out.println("Age is18Above Age: " + ages.subList(3, ages.size())); } }
Output Result
Age List: [10, 12, 15, 19, 23, 34] Age is18Below Age: [10, 12, 15] Age is18Above Age: [19, 23, 34]
In the above example, we created an ArrayList named ages. Here, we have used the subList() method to divide the ArrayList into two ArrayLists:Age is18Below AgeandAge is18Above Age.
Please note that we have used the ages.size() method to get the length of the ArrayList. For more information about the size() method, please visitJava ArrayList size().