List
列表中刪除null
的不一樣方法:拋磚引玉,先拋磚,大招在最後。java
當使用Java 7
或更低版本時,咱們能夠使用如下結構從列表中刪除全部空值:編程
@Test public removeNull() { List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null)); list.removeAll(Collections.singleton(null)); assertThat(list, hasSize(2)); }
null
將拋出java.lang.UnsupportedOperationException
的錯誤。從Java 8
或更高版本,從List
列表中刪除null
的方法很是直觀且優雅:網絡
@Test public removeNull() { List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null)); list.removeIf(Objects::isNull); assertThat(list, hasSize(2)); }
咱們能夠簡單地使用removeIf()構造來刪除全部空值。閉包
若是咱們不想更改現有列表,而是返回一個包含全部非空值的新列表,則能夠:性能
@Test public removeNull() { 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)); }
Apache Commons CollectionUtils
類提供了一個filter
方法,該方法也能夠解決咱們的目的。傳入的謂詞將應用於列表中的全部元素:測試
@Test public removeNull() { List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null)); CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); assertThat(list, hasSize(2)); }
Guava
中的Iterables
類提供了removeIf()
方法,以幫助咱們根據給定的謂詞過濾值。code
@Test public removeNull() { List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null)); Iterables.removeIf(list, Predicates.isNull()); assertThat(list, hasSize(2)); }
另外,若是咱們不想修改現有列表,Guava容許咱們建立一個新的列表:ip
@Test public removeNull() { 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)); }
@Test public removeNull() { 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)); }
List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null)); def re = list.findAll { it != null } assert re == ["A", "B"]
有興趣能夠讀讀Groovy中的閉包v8