BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to get sublist of an ArrayList with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

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

Syntax:

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.

Note:
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).

Example 1: Getting a sublist from an ArrayList

In the following example, we have an ArrayList al. We want to get a sublist starting from index 1 till index 3 from this ArrayList. To get this sublist, we are calling the subList() method like this: al.subList(1, 4).

As mentioned in the syntax of sublist(), the fromIndex is inclusive and toIndex is exclusive, which means index 1 is inclusive and index 4 is exclusive. This is why element present at index 1 is included in sublist, while element present at index 4 is excluded from ArrayList and elements are present till index 3.

We placed the code inside a try-catch block to catch any exception. In this program, indexes mentioned in the subList() method are valid so no exception raised. In the example 2 and 3, we will see how to handle exception when index values are invalid.

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

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

      //Addition of elements in ArrayList
      al.add("Steve");
      al.add("Justin");
      al.add("Ajeet");
      al.add("John");
      al.add("Arnold");
      al.add("Chaitanya");

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

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

      //Storing Sublist into a List
      List<String> list = al.subList(1, 4);
      System.out.println("SubList stored in List: " + list);
    }
    catch (IndexOutOfBoundsException e) {
      System.out.println("Exception while getting sublist: " + e);
    }

    catch (IllegalArgumentException e) {
      System.out.println("Exception while getting sublist: " + e);
    }
  }
}

Output:

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

Example 2: subList() method: IndexOutOfBoundsException

As mentioned in the beginning, if the specified indexes in subList() method are out of the range, this method throws IndexOutOfBoundsException. Exception occurs if index values satisfies this condition: (fromIndex < 0 || toIndex > size)

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

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

      //Addition of elements in ArrayList
      al.add("Steve");
      al.add("Justin");
      al.add("Ajeet");
      al.add("John");
      al.add("Arnold");
      al.add("Chaitanya");

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

      // The toIndex is 14 and size of the ArrayList is 6 so
      // toIndex > size, this will throw exception
      List<String> list = al.subList(1, 14);
      System.out.println("SubList: " + list);
    }
    catch (IndexOutOfBoundsException e) {
      System.out.println("Exception while getting sublist: " + e);
    }

    catch (IllegalArgumentException e) {
      System.out.println("Exception while getting sublist: " + e);
    }
  }
}

Output:
How to get sublist of an ArrayList with example

Example 3: subList() method: IllegalArgumentException

If the starting index is greater than the end index (fromIndex > toIndex) then IllegalArgumentException occurs. Let’s see the following example to understand when this exception occurs.

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

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

      //Addition of elements in ArrayList
      names.add("Paul");
      names.add("Rahul");
      names.add("Kevin");
      names.add("Smith");
      names.add("Rob");

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

      // Here fromIndex is 4 and toIndex is 2
      // fromIndex > toIndex, this will throw exception
      List<String> list = names.subList(4, 2);
      System.out.println("SubList: " + list);
    }
    catch (IndexOutOfBoundsException e) {
      System.out.println("Exception while getting sublist: " + e);
    }

    catch (IllegalArgumentException e) {
      System.out.println("Exception while getting sublist: " + e);
    }
  }
}

Output:
sublist of an ArrayList

Recommended Articles:

  • Add multiple items to an ArrayList
  • Difference between Array and ArrayList
  • Get subList of a Vector in Java
  • Get sublist of a LinkedList in Java
❮ Java Collections

Top Related Articles:

  1. Exception handling in Java with examples
  2. Vector Iterator example in Java
  3. How to loop HashMap in java
  4. How to Convert an array to ArrayList in java
  5. Constructor Overloading in Java with examples

Tags: Collections, Java-ArrayList

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Abhishek Basu says

    January 30, 2017 at 7:34 PM

    //Sublist to ArrayList
    ArrayList al2 = new ArrayList(al.subList(1, 4));

    How is the above method working? I know that the below would not work because of downcasting issues.

    ArrayList al2 = (ArrayList) (al.subList(1, 4));

    Reply
  2. Paal says

    September 28, 2017 at 9:01 AM

    Lets say I have a list of unknown length I want to get the whole list except the last element. Will it work to do this:
    ArrayList al2 = new ArrayList(al.subList(1, -2));

    Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap