Organizational Research By

Surprising Reserch Topic

How to get sublist of an ArrayList with example

In this tutorial we will see how to get a sublist from an existing ArrayList. We will be doing it using the subList method of ArrayList class.

List subList(int fromIndex, int toIndex)

Here fromIndex is inclusive and toIndex is exclusive. There are few important points regarding this method which I have shared at the end of this post.

Example of getting sub-list from an ArrayList

Points to Note in the below example:
The subList method returns a list therefore to store the sublist in another ArrayList we must need to type cast the returned value in same way as I did in the below example. On the other side if we are storing the returned sublist into a list then there is no need to type cast (Refer the example).

import java.util.ArrayList;
import java.util.List;
public class SublistExample {

 public static void main(String a[]){
     ArrayList<String> al = new ArrayList<String>();

     //Addition of elements in ArrayList

     System.out.println("Original ArrayList Content: "+al);

     //Sublist to ArrayList
     ArrayList<String> al2 = new ArrayList<String>(al.subList(1, 4));
     System.out.println("SubList stored in ArrayList: "+al2);

     //Sublist to List
     List<String> list = al.subList(1, 4);
     System.out.println("SubList stored in List: "+list);


Original ArrayList Content: [Steve, Justin, Ajeet, John, Arnold, Chaitanya]
SubList stored in ArrayList: [Justin, Ajeet, John]
SubList stored in List: [Justin, Ajeet, John]

The subList method throws¬†IndexOutOfBoundsException¬†‚Äď if the specified indexes are out of the range of ArrayList (fromIndex < 0 || toIndex > size).
IllegalArgumentException¬†‚Äď if the starting index is greater than the end point index (fromIndex > toIndex).

asked Jun 11, 2015 in Core java by rajesh
0 votes

Related Hot Questions

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.