比如要把一个LIST中的所有NULL值都取消,则可以:
1) JAVA 7及以下版本:
@Test
public removeAllNullsFromListWithJava7OrLower() {
List<String> list =
new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeAll(Collections.singleton(null));
assertThat(list, hasSize(2));
}
2) 如果是JAVA 8以上,可以更优雅
@Test
public removeAllNullsFromListWithJava8() {
List<String> list =
new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeIf(Objects::isNull);
assertThat(list, hasSize(2));
}
如果想用一个新得LIST去装载,则可以:
@Test
public removeAllNullsFromListWithJava8() {
List<String> list =
new ArrayList<>(Arrays.asList("A", null, "B", null));
List<String> newList = list.stream().filter(Objects::nonNull)
.collect(Collectors.toList());
assertThat(list, hasSize(4));
assertThat(newList, hasSize(2));
}
3) 也可以用著名得apache common工具库去做:
@Test
public removeAllNullsFromListWithApacheCommons() {
List<String> list =
new ArrayList<>(Arrays.asList("A", null, "B", null));
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
assertThat(list, hasSize(2));
}
4) GOOGLE GUVA库:
@Test
public removeAllNullsFromListUsingGuava() {
List<String> list =
new ArrayList<>(Arrays.asList("A", null, "B", null));
List<String> newList = new ArrayList<>(
Iterables.filter(list, Predicates.notNull()));
assertThat(list, hasSize(4));
assertThat(newList, hasSize(2));
}