一、removeIf用法
Java ArrayList removeIf() 方法用于删除所有满足特定条件的数组元素,removeIf() 方法的语法为:
arraylist.removeIf(Predicate<E> filter)
注:arraylist 是 ArrayList 类的一个对象。
参数说明:
filter - 过滤器,判断元素是否要删除
返回值:
如果元素被删除则返回 true。
JDK1.8中,Collection以及其子类新加入了removeIf方法,作用是按照一定规则过滤集合中的元素
举例:
public class RemoveIf {
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);
Collection<Map<String, Object>> collection = new ArrayList();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "小明");
map1.put("age", 30);
map1.put("sex", "男");
collection.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "小花");
map2.put("age", 26);
map2.put("sex", "男");
collection.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("name", "小红");
map3.put("age", 28);
map3.put("sex", "男");
collection.add(map3);
System.out.println("删除前的 collection : " + collection);
collection.removeIf(item -> (Integer) item.get("age") >= 28);
System.out.println("删除前的 collection : " + collection);
}
}
运行结果如下:
删除前的 ArrayList : [Google, Runoob, Taobao]
删除后的 ArrayList: [Google, Runoob]
删除前的 collection : [{
sex=男, name=小明, age=30}, {
sex=男, name=小花, age=26}, {
sex=男, name=小红, age=28}]
删除前的 collection : [{
sex=男, name=小花, age=26}]