Remove Slice from a List in Java

In this post, we will see how to remove slice from a list between two specified indexes in Java.


 

For example, if the list is ["C", "C++", "Java", "Python", "Go"] and fromIndex = 1 and endIndex = 3, the resultant list would have all elements removed between [fromIndex, endIndex] i.e. ["C", "Go"].

 

1. Naive solution

Naive solution would be to move backwards in the list using a for-loop and remove all elements from it between specified range. Please note that we should move backwards in the list as moving forward might cause to skip few elements in it and result in undesired result.

 

Download   Run Code

 

2. List.clear() + List.subList()

List interface provides clear() method that removes all elements from the specified list. We can use it along with the subList() method (that returns a partial view of the list) to remove a range of elements from a list as shown below:

 

Download   Run Code

 

3. List.removeAll() + List.subList()

List interface also provides removeAll() method that removes all elements in the list that are contained in the specified collection. We can pass a sublist returned by subList() method to it to remove elements between specified indexes.

 

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