Java8新特性之集合removeIf(Predicate<? super E> filter)

来源:互联网 发布:vscode 离线插件包 编辑:程序博客网 时间:2024/04/29 21:25

在使用阿里的代码规范检测插件后,不得不承认代码的质量提高了很多,在这里也推荐给大家:
https://www.cnblogs.com/Mr-Rocker/p/7676694.html

这里遇到一个问题,在我写迭代器的时候通常是这么写的:

List <Integer> list = new ArrayList <>();list.addAll(Arrays.asList(1, 2, 3, 4, 5));final Iterator <Integer> iterator = list.iterator();while (iterator.hasNext()){    final Integer i = iterator.next();    if(2 == i){     it.remove();    }}

但是阿里的插件检测出代码不规范,所以我换了一种写法:

final Iterator <Integer> iterator = list.iterator();while (iterator.hasNext()){    final Integer i = iterator.next();    if(2 == i){     it.remove();    }}

还是警告我不规范。。。
于是我根据他的建议改写成:

list.removeIf(i -> 2 == i);

确实清爽了许多,简洁了许多,最关键的是很有效。

后来看了下源码:

/**  * 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; }

所以,以后还是用新方法吧,与时俱进哦。

原创粉丝点击