removeIf用法
removeIf用法
-
Java ArrayList removeIf() 方法:
-
removeIf() 方法用于删除所有满足特定条件的数组元素。
removeIf() 方法的语法为:
arraylist.removeIf(Predicate<E> filter)
注:arraylist 是 ArrayList 类的一个对象。
参数说明:
- filter - 过滤器,判断元素是否要删除
返回值:
如果元素被删除则返回 true。
-
举例
import java.util.*; class Main { public static void main(String[] args){ // 创建一个动态数组 ArrayList<String> sites = new ArrayList<>(); sites.add("Google"); sites.add("Runoob"); sites.add("Taobao"); System.out.println("ArrayList : " + sites); // 删除名称中带有 Tao 的元素 sites.removeIf(e -> e.contains("Tao"));; System.out.println("删除后的 ArrayList: " + sites); } }
// 删除所有偶数元素 numbers.removeIf(e -> (e % 2) == 0);;
-
-
JDK1.8中,
Collection
以及其子类新加入了removeIf
方法,作用是按照一定规则过滤集合中的元素 :Collection<Person> collection = new ArrayList(); collection.add(new Person("张三", 22, "男")); collection.add(new Person("李四", 19, "女")); collection.add(new Person("王五", 34, "男")); collection.add(new Person("赵六", 30, "男")); collection.add(new Person("田七", 25, "女")); collection.removeIf( person -> person.getAge() >= 30 );//过滤30岁以上的求职者
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库