Write a Java program to extract a portion of a array list


This Java code demonstrates how to extract a portion of an ArrayList using the subList() method of the List interface. First, the code creates a new ArrayList called list_col and adds five elements to it using the add() method. Then, it prints out the entire list using the System.out.println() statement.

Next, the code creates a new list called sub_list using the subList() method, which takes two arguments - the starting index (inclusive) and the ending index (exclusive) of the sublist. In this case, it extracts the first three elements of the list_col ArrayList (indices 0, 1, and 2) and stores them in the new sub_list list.

Finally, the code prints out the sub_list using the System.out.println() statement to show the extracted portion of the original list.

Source Code

import java.util.*;
public class Extract_Portion
{
	public static void main(String[] args)
	{
		List<String> list_col = new ArrayList<String>();
		list_col.add("Red");
		list_col.add("Green");
		list_col.add("Orange");
		list_col.add("White");
		list_col.add("Black");
		System.out.println("Given list: " + list_col);
		List<String> sub_list = list_col.subList(0, 3);
		System.out.println("List of First Three Elements: " + sub_list);
	}
}

Output

Given list: [Red, Green, Orange, White, Black]
List of First Three Elements: [Red, Green, Orange]

Example Programs