前言:
介绍一下使用普通的Java,Java 8 lambda和一些第三方库从Java List<?>中删除空值。
1. Java 7或更低版本:
public void removeAllNullsFromListWithJava7OrLower() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeAll(Collections.singleton(null));
System.out.print(list);// [A, B]
}
//注意:
// 从不可变列表中删除空值将抛出java.lang.UnsupportedOperationException。
2. Java 8或更高版本(推荐):
public void removeAllNullsFromListWithJava8() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeIf(Objects::isNull);
System.out.print(list);// [A, B]
}
//如果不想使用 removeIf 也可以:
public void removeAllNullsFromListWithJava8() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
List<String> newList = list.stream().filter(Objects::nonNull) .collect(Collectors.toList());
System.out.print(newList );// [A, B]
}
3. Apache Commons:
Apache Commons CollectionUtils类提供了一个过滤器(Iterable,Predicate)方法。
public void removeAllNullsFromListWithApacheCommons() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
System.out.print(list);// [A, B]
}
4.Google Guava:
Guava中的Iterables类提供了removeIf(Iterable,Predicate)方法。
public void removeAllNullsFromListUsingGuava() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
Iterables.removeIf(list, Predicates.isNull());
System.out.print(list);// [A, B]
}
//或者,如果不想修改现有列表,Guava允许我们创建一个新列表:
public void removeAllNullsFromList() {
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
List<String> newList = new ArrayList<>(Iterables.filter(list, Predicates.notNull()));
System.out.print(newList);// [A, B]
}