如何在 Java 中的 lambda 表示式中使用 ArrayList?\n


Lambda expression 是一種內聯程式碼,可以實現功能性 介面 而不建立匿名類。ArrayList 可用於儲存大小動態的元素集合

在下面的程式中,我們使用removeIf() 方法移除了年齡小於或等於 20 的ArrayList 元素。此方法引入到Java 8 版本中,用於從集合中移除滿足某個條件的所有元素。

語法

public boolean removeIf(Predicate filter)

引數filter 是一個Predicate。如果給定的謂詞滿足條件,則元素可以被移除。如果移除了元素,則此方法返回booleantrue ;否則返回false

示例

import java.util.*;

public class LambdaWithArrayListTest {
   public static void main(String args[]) {
      ArrayList<Student> studentList = new ArrayList<Student>();
      studentList.add(new Student("Raja", 30));
      studentList.add(new Student("Adithya", 25));
      studentList.add(new Student("Jai", 20));
      studentList.removeIf(student -> (student.age <= 20)); // Lambda Expression
      System.out.println("The final list is: ");
      for(Student student : studentList) {
         System.out.println(student.name);
      }
   }
   private static class Student {
      private String name;
      private int age;
      public Student(String name, int age) {
         this.name = name;
         this.age = age;
      }
   }
}

輸出

The final list is:
Raja
Adithya

更新於:11-Jul-2020

2 千次瀏覽

開啟你的 事業

完成課程即可獲得認證

開始
廣告