Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Find SubList of ArrayList - Testingpool

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...