Java8 新特性之集合: removeIf(Predicate

下边是JDK1.8.0_121中接口Collection的部分源码:

/** * Removes all of the elements of this collection that satisfy the given * predicate. Errors or runtime exceptions thrown during iteration or 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 elements cannot be removed * from this collection. Implementations may throw this exception if a * matching element cannot be removed or if, in general, removal is not * supported. * @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;
 }

下边是翻译后的源码(英语渣,如有错误,请指正):

/** * 移除集合中满足给定条件的所有元素,错误或者运行时异常发生在迭代时或者把条件传递给调用者的时候。 * * @implSpec * 默认的实现贯穿了使用迭代器iterator的集合的所有元素。每一个匹配的元素都将被用Iterator接口中的 * remove()方法移除。如果集合的迭代器不支持移除,则在第一次匹配时就会抛出异常 UnsupportedOperationException * * @param filter 令元素移除成功的条件 * @return {@code true} 如果所有的元素都被移除 * @throws NullPointerException 如果有一个过滤器是空的 * @throws UnsupportedOperationException 如果元素不能被从该集合中移除。如果一个匹配元素不能被移除, * 通常来说,它就不支持移除操作,这时可能抛出这个异常。 * @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;
 }

下边是实际练习代码

public static void main(String[] args) {

    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.removeIf(s -> s%2==0);               // 过滤掉模2等于0的数
    list.forEach(s -> System.out.println(s)); // 输出 1 3

    List<String> strings = new ArrayList<>();
    strings.add("ab");
    strings.add("ac");
    strings.add("bc");
    strings.add("cd");
    Predicate<String> predicate = (s) -> s.startsWith("a"); // 这里单独定义了过滤器
    strings.removeIf(predicate);                            // 过滤掉以"a"开头的元素
    strings.forEach(s -> System.out.println(s));            // 输出 bc cd
}
    原文作者:HelloMrZheng
    原文地址: https://blog.csdn.net/HelloMrZheng/article/details/70148300
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞