src/share/classes/java/util/Collection.java
Print this page
rev 6962 : [mq]: collections
@@ -23,10 +23,12 @@
* questions.
*/
package java.util;
+import java.util.function.Predicate;
+
/**
* The root interface in the <i>collection hierarchy</i>. A collection
* represents a group of objects, known as its <i>elements</i>. Some
* collections allow duplicate elements and others do not. Some are ordered
* and others unordered. The JDK does not provide any <i>direct</i>
@@ -371,10 +373,42 @@
* @see #contains(Object)
*/
boolean removeAll(Collection<?> c);
/**
+ * Removes all of the elements of this collection which match the provided
+ * predicate. Exceptions thrown by the predicate are relayed to the caller.
+ *
+ * @implSpec
+ * The default implementation traverses all elements of the collection using
+ * its {@link #iterator}. Each matching element is removed using
+ * {@link Iterator#remove()}. If the collection's iterator does not
+ * support removal then an {@code UnsupportedOperationException} will be
+ * thrown on the first matching element.
+ *
+ * @param filter a predicate which returns {@code true} for elements to be
+ * removed
+ * @return {@code true} if any elements were removed
+ * @throws NullPointerException if the specified filter is null
+ * @throws UnsupportedOperationException if the {@code removeIf}
+ * method is not supported by this collection
+ * @since 1.8
+ */
+ default boolean removeIf(Predicate<? super E> filter) {
+ Objects.requireNonNull(filter);
+ boolean removed = false;
+ final Iterator<E> each = iterator();
+ while (each.hasNext()) {
+ if (filter.test(each.next())) {
+ each.remove();
+ removed = true;
+ }
+ }
+ return removed;
+ }
+
+ /**
* Retains only the elements in this collection that are contained in the
* specified collection (optional operation). In other words, removes from
* this collection all of its elements that are not contained in the
* specified collection.
*