Home » Java List sublist() Method with Examples

Java List sublist() Method with Examples

by Online Tutorials Library

Java List sublist() Method

The sublist() method of List Interface returns a view of the portion of this list between the inclusive and exclusive parameters. This method eliminates the need for explicit range operations.

Syntax

Parameters

The parameters ‘fromIndex’ and ‘toIndex’ represent the low and high endpoint of the subList.

Return

The subList() method returns a view of the specified range within this list.

Throws:

IndexOutOfBoundsException– This exception will throw for an illegal endpoint index value, i.e, fromIndex < 0 or toIndex> size or fromIndex > toIndex.

Example 1

Test it Now

Output:

List : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  Elements from 2 index position to 7 index position : [3, 4, 5, 6, 7]  

Example 2

Test it Now

Output:

Total alphabets : 26  Exception in thread "main" java.lang.IllegalArgumentException: fromIndex(18) >toIndex(12)  atjava.util.SubList.<init>(AbstractList.java:624)  atjava.util.AbstractList.subList(AbstractList.java:484)  at com.tutorAspire.JavaListSubListExample2.main(JavaListSubListExample2.java:12)  

Example 3

Test it Now

Output:

Total alphabets : 26  Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex = -1  atjava.util.SubList.<init>(AbstractList.java:620)  atjava.util.AbstractList.subList(AbstractList.java:484)  at com.tutorAspire.JavaListSubListExample3.main(JavaListSubListExample3.java:13)  
Next TopicJava List

You may also like