How to get Sublist from ArrayList

In this tutorial we will see, How can you get Sublist from ArrayList or how can we generate the ArrayList from existing ArrayList.

We can do this using subList() method of ArrayList class.

List subList(int fromIndex, int toIndex)


Get Sublist from ArrayList in Java

You can get the Sublist using this method by specifying the start and end index of range.

Let’s understand this with an easy example-


Orignal ArrayList –[15, 20, 25, 5, 12]
Sublist is –[25, 5]


In the above example, First, we create the ArrayList and inserted the elements inside the ArrayList up to index 4.

Then we created the another ArrayList to contain the List return by subList() method.  In the SubList() method, we have passed the start and end Index range and print the SubList . Using this we can create the sublist from ArrayList.

Here, We need to be careful about the start and end index range in the SubList() method.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 endpoint index (fromIndex > toIndex).


Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply