Java program to create a sub list from an ArrayList

In this Java program, we are going to learn how to create a sub list from an ArrayList? By IncludeHelp Last updated : December 31, 2023

Problem statement

Given an ArrayList, and we have to create a sub list from it using Java program.

Creating a sub list from an ArrayList

To create a sub list from an ArrayList, you can use the ArrayList.subList() method by passing the starting and ending indices of the ArrayList.

Below is the syntax of ArrayList.subList() method

ArrayList.subList(start_index, end_index);

Here, start_index and end_index are the indexes for 'from' and 'to' index. The list, returned by ArrayList.subList() will be stored in an object of "List".

Java program to create a sub list from an ArrayList

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

public class Main {
  public static void main(String[] args) {
    //ArrayList object
    ArrayList arrList = new ArrayList();

    //adding elements 
    arrList.add("100");
    arrList.add("200");
    arrList.add("300");
    arrList.add("400");
    arrList.add("500");

    //adding elements in List using 
    //subList method
    List oList = arrList.subList(1, 3);

    //displaying elements of sub list
    System.out.println("Elements of sub list: ");
    for (int i = 0; i < oList.size(); i++)
      System.out.println(oList.get(i));
  }
}

Output

The output of the above example is:

Elements of sub list: 
200
300

Java ArrayList Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.