Sublist from ArrayList
In this article, we will understand how to get sublist from the existing ArrayList.
We just need to specify the from_Index and to_Index to specify the range of sublist using a method defined in ArrayList as below
- List subList(int fromIndex, int toIndex)
List subList(int fromIndex, int toIndex)
Note :
fromIndex is inclusive and toIndex is exclusive The return value of subList method is again another list
Example :
- import java.util.*;
- public class ArrayListSubList {
- public static void main(String[] args) {
- ArrayList<Integer> list = new ArrayList<Integer>();
- list.add(14);
- list.add(7);
- list.add(21);
- list.add(28);
- list.add(35);
- list.add(42);
- System.out.println("Original ArrayList : "+list);
- List<Integer> subList = list.subList(1, 3);
- System.out.println("SubList from ArrayList: "+subList);
- }
- }
import java.util.*; public class ArrayListSubList { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(14); list.add(7); list.add(21); list.add(28); list.add(35); list.add(42); System.out.println("Original ArrayList : "+list); List<Integer> subList = list.subList(1, 3); System.out.println("SubList from ArrayList: "+subList); } }
Note :
The subList method throws IndexOutOfBoundsException – If the specified indexes are out of the range of ArrayList (fromIndex < 0 or toIndex > size). IllegalArgumentException – If the starting index is greater than the end index (fromIndex > toIndex)
.
This is useful if we want to get sublist from the mainlist within some range indexes.