removeIf用法

   removeIf用法
  • Java ArrayList removeIf() 方法:

    1. removeIf() 方法用于删除所有满足特定条件的数组元素

      removeIf() 方法的语法为:

      arraylist.removeIf(Predicate<E> filter)
      

      注:arraylist 是 ArrayList 类的一个对象。

      参数说明:

      • filter - 过滤器,判断元素是否要删除

      返回值

      如果元素被删除则返回 true。

    2. 举例

      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岁以上的求职者
    
posted @ 2022-08-02 15:30  大于昨天  阅读(9308)  评论(0编辑  收藏  举报