To create Sublist from ArrayList in java, we need to use the subList(int fromIndex,int toIndex) method provided by ArrayList. We will see the example on how to use the subList method.
public List<E> subList(int fromIndex,int toIndex) returns a new List.
Example : Create Sublist from ArrayList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.kscodes.sampleproject; import java.util.ArrayList; import java.util.List; public class ArrayListSubListExample { public static void main(String[] args) { // Create an ArrayList List<String> arrayList1 = new ArrayList<>(); arrayList1.add("Java"); arrayList1.add("JSP"); arrayList1.add("JavaScript"); arrayList1.add("JQuery"); arrayList1.add("Spring MVC"); arrayList1.add("Hibernate"); arrayList1.add("KnockoutJs"); System.out.println("Create Sublist from Element 2 to 4"); List<String> subList1 = arrayList1.subList(2, 4); System.out.println(subList1); System.out.println("------------------------------------"); System.out.println("Create Sublist from Element 3 to 7"); List<String> subList2 = arrayList1.subList(3, 7); System.out.println(subList2); System.out.println("------------------------------------"); System.out.println("Try Creating Sublist that has out of range values and see what is the error"); List<String> subList3 = arrayList1.subList(3, 10); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Create Sublist from Element 2 to 4 [JavaScript, JQuery] ------------------------------------ Create Sublist from Element 3 to 7 [JQuery, Spring MVC, Hibernate, KnockoutJs] ------------------------------------ Try Creating Sublist that has out of range values and see what is the error Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 10 at java.util.ArrayList.subListRangeCheck(Unknown Source) at java.util.ArrayList.subList(Unknown Source) at com.kscodes.sampleproject.ArrayListSubListExample.main(ArrayListSubListExample.java:35) |