的λ 表达 是可实施一个内联代码功能 接口 而不创建匿名类。ArrayList可用于存储元素的动态大小集合。
在下面的程序中,我们使用removeIf()方法删除了年龄小于或等于20的ArrayList 元素。在Java 8中引入了此方法,以从满足条件的集合中删除所有元素。
public boolean removeIf(Predicate filter)
参数过滤器 是Predicate。如果给定谓词满足条件,则可以删除该元素。如果删除元素,则此方法返回布尔 值true ,否则返回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