Find SubList of ArrayList

In the previous post, we have seen how to sort the arrayList by using comparable and comparator.In this post, we will see how to get a sublist from a ArrayList.

Find SubList of ArrayList:

We have method called ‘sublist’ where we can define the range of sublist which needs to be acquired.

Syntax:

List subList(int fromIndex, int toIndex)

fromIndex: Start position of the range

toindex: End position of the range

Sublist method returns a type of list, so to store a list into arraylist we need to type cast the returned value. If list gets stored in the List directly , then there is no need to typecast.

It will be more clear with the below example.

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

public class ArrayListEx {

	public static void main(String[] args) {
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Orange");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Grapes");
		fruits.add("Banana");
		System.out.println("List of total fruits: "+fruits);

		ArrayList<String> sub1 = new ArrayList<String>(fruits.subList(2, 4));
		System.out.println("SubList of fruits stored in arrayList : "+sub1);
		
		List<String> sub2 =  fruits.subList(2, 4);
		System.out.println("SubList of fruits stored in List directly : "+sub2);
	}
}

Output:

List of total fruits: [Orange, Mango, Apple, Grapes, Banana] SubList of fruits stored in arrayList : [Apple, Grapes] SubList of fruits stored in List directly : [Apple, Grapes]

Note:
The subList method throws IndexOutOfBoundsException – if the specified indexes are out of the range of ArrayList (fromIndex < 0 || toIndex > size).
IllegalArgumentException – if the starting index is greater than the end point index (fromIndex > toIndex).

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...