C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programs » Java ArrayList programs

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? This example contains a list of some elements and creates a sub list.
Submitted by IncludeHelp, on October 21, 2017

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

ArrayList. subList()

It is used to return a sub list (also, consider as List).

Syntax:

ArrayList. subList(start_index, end_index);

start_index, end_index are the indexes for 'from' and 'to' index

The list, returned by ArrayList.subList() will be stored in an object of "List".

Consider the program

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

public class subListExample{
	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

Elements of sub list: 
200
300






COMMENTS