In this article we will learn how to get a sublist from an ArrayList in Java.
Java Program to Get Sublist of an ArrayList
Sublist means a portion of a list.
In java, subList()
is a builtIn method of java.util.ArrayList
class that is used to extract a portion of an Arraylist from the specified index beginIndex(inclusive)
to the specified index endIndex(exclusive)
.
Like subList(begin)
Parameters:
- beginIndex: It is the first parameter of the method. It is the start index of the sublist which is inclusive.
- endIndex: It is the second parameter of the method. It is the end Index of the sublist which is exclusive.
Syntax:
public List subList( int beginIndex ,int endIndex)
Returns: A view within the range specified in the parameters.
But while using subList() method, we have to keep look on two exceptions mainly.
Those are,
- IndexOutOfBoundsException: If the specified indexes are out of the range of ArrayList (beginIndex < 0 || endIndex > listsize).
- IllegalArgumentException: If the starting index is greater than the end point index (beginIndex > endIndex).
Now let’s see program to understand it more clearly.
Method: Java Program to Get Sublist of an ArrayList By Using subList() Method
Approach:
- Declare an ArrayList of String say
arraylist
- Add elements into the Arraylist using
add()
method. - Extract a subList from an ArrayList by using
subList()
Also, typecast the resulting sublist. - Extract a sublist from List using
subList()
method without typecasting.
Program:
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String args[]) { //ArrayList declared ArrayList<String> arraylist = new ArrayList<String>(); //Addition of elements in ArrayList arraylist.add("Java"); arraylist.add("Scala"); arraylist.add("Python"); arraylist.add("Kotlin"); //Display elements of original ArrayList System.out.println("Original ArrayList elements: "+ arraylist); //Extracting Sublist From ArrayList ArrayList<String> sl1 = new ArrayList<String>(arraylist.subList(1, 4)); System.out.println("SubList stored in ArrayList: "+ sl1); //Extracting Sublist from List List<String> sl2 = arraylist.subList(1, 3); System.out.println("SubList stored in List: "+ sl2); } }
Output: Original ArrayList elements: [Java, Scala, Python, Kotlin] SubList stored in ArrayList: [Scala, Python, Kotlin] SubList stored in List: [Scala, Python]
Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.