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 and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.