Java_collection JDK8 中 collection接口的RemoveIf方法;Iterator接口forEachRemaining方法

通过下面例子学习collection接口的RemoveIf方法;Iterator接口forEachRemaining方法

package cn.ling.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

//collection 接口 removeIf方法  删除满足某个条件的元素
public class RemoveIf {
    public static void main(String[] args) {
        List<String> strList = new ArrayList<>();
        strList.add("apple");
        strList.add("apple1");
        strList.add("apple2");
        strList.add("apple3");
        strList.add("apple4");
        strList.add("banana");
        strList.add("1banana");
        strList.add("2banana");
        strList.add("3banana");
        strList.add("43banana");

        Iterator<String> iterators = strList.iterator();
        while (iterators.hasNext()){
            System.out.print(iterators.next()+ "  ");
        }

        System.out.println();
        System.out.println("--------------------------------");

        strList.iterator().forEachRemaining((str)-> System.out.print(str+ "  "));

        strList.removeIf((str)-> str.startsWith("a"));

        System.out.println();
        System.out.println("--------------------------------");
        strList.iterator().forEachRemaining((str)->System.out.print(str+ "  "));
    }
}

这个两个方法都要是用到Lambda表达式。

forEachRemaining

相当于循环执行目标函数的实现

default void forEachRemaining(Consumer<? super E> action) {
     Objects.requireNonNull(action);
     while (hasNext())
     	 //执行目标函数的函数体 Consumer是函数式接口
         action.accept(next());
 }
strList.iterator().forEachRemaining((str)-> System.out.print(str+ "  "));

上面写法不懂,可以参考:https://blog.csdn.net/lingyiwin/article/details/109212540

removeIf

实现过滤筛选的功能

default boolean removeIf(Predicate<? super E> filter) {
    Objects.requireNonNull(filter);
    boolean removed = false;
    final Iterator<E> each = iterator();
    while (each.hasNext()) {
    	//如果匹配成功 执行remove方法
        if (filter.test(each.next())) {
            each.remove();
            removed = true;
        }
    }
    return removed;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EngineerForSoul

你的鼓励是我孜孜不倦的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值