Get Sublist of a List in Java

In this post, we will see get how to get sublist of a list between two specified indexes.


 

1. Naive solution

Naive solution would be to add elements from the original list that are present between the specified indexes to the sublist.

 

Download   Run Code

 

2. List.sublist()

We can also use sublist() method provided by the List interface that returns a “view” of the portion of the list between the specified indexes.

 

Download   Run Code

 

2.1. java.lang.IndexOutOfBoundsException

The subList() method throws IndexOutOfBoundsException if starting or ending index is illegal. For instance,

  • start < 0
  • end > list.size()
  • start > end

To avoid IndexOutOfBoundsException from happening, we can check if indexes are within proper bounds before passing to sublist() as shown below:

 

Download   Run Code

 

2.2. ConcurrentModificationException

Since the list returned by list.subList() is backed by the list, any non-structural changes (that does not change the size of the list) in the sublist are reflected in the original list and vice-versa. If the backing list is structurally modified in any way, the behavior of the list is undefined and ConcurrentModificationException may be thrown.

 

Download   Run Code

Output:

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1231)
at java.util.ArrayList$SubList.listIterator(ArrayList.java:1091)
at java.util.AbstractList.listIterator(AbstractList.java:299)
at java.util.ArrayList$SubList.iterator(ArrayList.java:1087)
at java.util.AbstractCollection.toString(AbstractCollection.java:454)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at ListUtil.main(Main.java:23)

 
The solution to this problem is to create a new List from the returned view by subList() as shown below:

 

Download   Run Code

 
References: List Javadoc SE 8

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz