Remove all the strings in an array list containing certain characters

Viewed 535

so i have an array list that contains strings such as:

ArrayList<String> list = new ArrayList<>();
list.add("bookshelf");
list.add("bookstore");
list.add("library");
list.add("pencil");

Now i wanna search and remove all the strings in the arraylist that contain the word "book" in them. As far as i understand list.remove("book"); will only search for the particular string "book" and not the strings that contain the word "book". How can i solve this?

2 Answers

You can use removeIf like this:

list.removeIf(s -> s.contains("book"));

Note: this answers applies to Java version 7 and below (of course that it will work for higher versions as well but YCF_L's answer is simpler to implement in versions 8 and above).

The requirement is to iterate the list, check every element, and if it answers a certain condition: remove it.

Since this is the case we fall into a risky scenario where we modify the list while iterating it which is problematic because when we remove an element in the list its size changes.

In order to work around this problem we can iterate the list by index from the last element and back until the first one, this way, removing an element at index n will not effect accessing any element at index < n.

I'll leave the implementation details to you in order not to "spoon feed" and destroy your exercise :)

Related