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.

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

Print Friendly, PDF & Email
Sort ArrayList of Objects using Comparable and Comparator interface
Find out first and last occurrence of elements in ArrayList
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *