November 27, 2016 Leave a comment
Java 8 introduces a new method available for Collection types: removeif(). It accepts a predicate which defines the condition on which the elements should be removed. It returns a boolean where a true response means that at least one item has been removed and false otherwise:
Collection<String> stringStack = new Stack<>(); stringStack.add("Hello"); stringStack.add("my"); stringStack.add("dear"); stringStack.add("world"); stringStack.removeIf(s -> s.contains("ll"));
The above example will remove “Hello” from the list stack.
Note that not all collections support item removal. In that case the method will throw an UnsupportedOperationException in case an attempt is made to remove a matching element. The ArrayList is one such collection:
Collection<String> asList = Arrays.asList("hello", "my", "dear", "world"); asList.removeIf(s -> s.contains("ll"));
This will throw an exception unfortunately as the Array.asList method returns an ArrayList of type java.util.Arrays.ArrayList (which is read only and fixed size) and not the classic java.util.ArrayList (resizable and item-removable) – based on a comment by Juanito below.
View all posts related to Java here.