Write a Java program to get SubList from ArrayList


This Java program demonstrates how to get a sublist from an ArrayList, display the elements of the sublist, remove an element from the sublist, and print the original ArrayList. Here's how the code works:

  • An ArrayList named col_list of type String is created and several strings are added to it using the add() method.
  • A sublist of the original ArrayList is created using the subList() method of the List interface. The first argument is the starting index of the sublist, and the second argument is the ending index (exclusive) of the sublist.
  • The elements of the sublist are displayed using a for loop and the get() method.
  • An element is removed from the sublist using the remove() method, which returns the removed element.
  • The removed element is printed.
  • The elements of the original ArrayList are displayed using a for loop and the get() method.
  • The output shows the elements of the sublist before and after removing an element, as well as the elements of the original ArrayList after removing an element from the sublist.

Note that the subList() method returns a view of the original ArrayList, which means that any changes made to the sublist are reflected in the original ArrayList, and vice versa.

Source Code

import java.util.ArrayList;
import java.util.List;
public class Get_SubList
{
	public static void main(String[] args)
	{
		ArrayList<String> col_list = new ArrayList<String>();
 
		col_list.add("Blue");
		col_list.add("Green");
		col_list.add("Pink");
		col_list.add("Black");
		col_list.add("Red");
		col_list.add("orange"); 
		col_list.add("White"); 
 
		List<String> cl = col_list.subList(1,5);
 
		//display elements of sublist.
		System.out.println("Display Elements of Sublist Contains... ");
		for(int i=0; i< cl.size() ; i++)
		{			
			System.out.println(cl.get(i));
		}
 
		//remove one element from sub list
		Object obj = cl.remove(2);
		System.out.println("Removed from sub list is : "+obj);
 
		//print original ArrayList
		System.out.println("After removing from SubList ArrayList contains.. ");
		for(int i=0; i< col_list.size() ; i++)
		{
			System.out.println(col_list.get(i));
		}
	}
}

Output

Display Elements of Sublist Contains...
Green
Pink
Black
Red
Removed from sub list is : Black
After removing from SubList ArrayList contains..
Blue
Green
Pink
Red
orange
White

Example Programs