当前位置:网站首页>集合删除元素技巧 removeIf

集合删除元素技巧 removeIf

2022-06-10 22:39:00 Li_XiaoJin

removeIf

removeIf() 是从 JDK1.8 开始提供的。

查看 API 文档:

删除满足给定谓词的此集合的所有元素。 在迭代或谓词中抛出的错误或运行时异常被转发给调用者。

之前我们删除 List 中的元素的话,一般使用循环遍历实现。今天发现 removeIf 很好用,记录一下。

以前做法:

        List<String> testList = new ArrayList<>();
        Iterator<String> it = testList.iterator();
        while (it.hasNext()) {
            if ("aa".equals(it.next())) {
                it.remove();
            }
        }

现在可以使用:

        testList.removeIf(s -> "aa".equals(s));
    // 或者
        testList.removeIf("aa"::equals);

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可 Links:https://lixj.fun/archives/list删除元素技巧removeif

原网站

版权声明
本文为[Li_XiaoJin]所创,转载请带上原文链接,感谢
https://cloud.tencent.com/developer/article/2020539