Get Sub List of Java ArrayList Example

In this tutorial we will learn how to get a sublist from an existing list. We will use the subList() method of java.util.ArrayList to achieve this.

Signature

public List subList(int fromIndex,int toIndex) 

This method returns a view of the portion of this list between the specified fromIndex(inclusive) and toIndex(exclusive), If fromIndex and toIndex are equal, then the returned list will be empty. Throws IndexOutOfBoundsException if an endpoint index value is out of range (fromIndex < 0 || toIndex > size) and
IllegalArgumentException if the endpoint indices are out of order (fromIndex > toIndex)

Example

The following example shows the usage of java.util.Arraylist.sublist(fromIndex,toIndex) method.

import java.util.ArrayList;
import java.util.List;

public class ArrayListSubListExample
{
	public static void main(String[] args) { 
        // Create ArrayList al1 object
        ArrayList al1 = new ArrayList();
        
        //adding elements to al1
        al1.add("String 1");
        al1.add("String 2");
        al1.add("String 3");
        al1.add("String 4");
        al1.add("String 5");
        al1.add("String 6");
        al1.add("String 7");
        
        System.out.println("**Contents of al1**");
        for(String val: al1)
        {
        	System.out.println(val);
        }

        // Sublist to ArrayList
        ArrayList al2 = new ArrayList(al1.subList(2,4));
        System.out.println("**Contents of al2**");
        for(String val: al2)
        {
        	System.out.println(val);
        }
        
       //Sublist to List
        List list1 = al1.subList(2,5);
        System.out.println("**Contents of list1**");
        for(String val: list1)
        {
        	System.out.println(val);
        }
   }
}

Output

**Contents of al1**
String 1
String 2
String 3
String 4
String 5
String 6
String 7
**Contents of al2**
String 3
String 4
**Contents of list1**
String 3
String 4
String 5

Leave a Reply

Your email address will not be published. Required fields are marked *