Remove all items from ArrayList after a specific item

I have an array list

ArrayList<String> list=new ArrayList<String>();
  list.add("Apple"); 
  list.add("Ball");  
  list.add("Cat");  
  list.add("dog");  
  list.add("Egg");

And I want to remove all items after "Cat".

Is there any way to do that?

1 answer

  • answered 2017-06-17 19:12 janos

    You could get a subList(...) of the remaining elements, and clear() it:

    int index = list.indexOf("Cat");
    if (index > -1) {
        list.subList(index + 1, list.size()).clear();
    }
    

    I see other answer attempts are trying to use remove and removeAll methods. That's not efficient, because the remove(Object) and removeAll(Collection) methods try match elements in the list, which requires scanning the entire list. Worse, if elements may appear multiple times, then those techniques may incorrectly remove elements before the target too. Using subList and clear is correct, efficient and simple.