在 ArrayList 的源代码中,有一个名为 removeIf
函数,该函数需要传递一个 Predicate
参数,Predicate
是 java.util.function
包中一个非常有用的接口,而这个接口是专门用来传递一个 lambda 表达式。下面我将会用这个 ArrayList 中的 removeIf 函数来删除一个 List 中的所有 null 元素
public class RemoveIfTest {
public static void main(String[] args) {
List<String> strList = new ArrayList<>(Arrays.asList("test1", "test2", null, null, "test3", null, "test4"));
// 下面的代码相当于 strList.removeIf(e -> e == null);
strList.removeIf(Objects::isNull);
System.out.println(strList);
}
}
这样,一个 "test1", "test2", null, null, "test3", null, "test4"
的列表,最后输出的结果为 [test1, test2, test3, test4]
成功剔除了列表中所有为 null 的元素。