How to get sublist from ArrayList

In this tutorial We will learn how to get sublist from list java . To find sublist in list java we use java ArrayList subList() method. 

Syntax :

public List<E> subList(int fromIndex, int toIndex) {


This method returns a view of the portion of this list between the given fromIndex, inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
The returned list supports all of the optional list operations.

Parameters: It take two parameter as arguments

  • fromIndex  – low endpoint (inclusive) of the subList
  • toIndex – high endpoint (exclusive) of the subList
    Returns Value : It return a view of the specified range within this list

Exception : It throws following exception

  • IndexOutOfBoundsException – for an illegal endpoint index value (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
  • IllegalArgumentException – if the endpoint indices are out of order (fromIndex > toIndex)

Let’s see java ArrayList subList() method with example by code

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

public class GetSubList {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
// print arraylist
System.out.println("arrayList is = " + arr);

* Returns a view of the portion of this list between the specified
* fromIndex, inclusive, and toIndex, exclusive

List<String> list=arr.subList(2,4);
System.out.println("sub list is="+list);




arrayList is = [c, php, html, java, mysql]

sub list is=[html, java]

Leave a Reply

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

1 + 2 =