比如要把一个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));
}
博客介绍了在Java中去除List里所有NULL值的方法。包括Java 7及以下版本的处理方式,Java 8以上更优雅的做法,还提及可用著名的apache common工具库以及GOOGLE GUVA库来实现。
1793

被折叠的 条评论
为什么被折叠?



