刪除List中null的N種方法--最後放大招

  • List列表中刪除null的不一樣方法:

拋磚引玉,先拋磚,大招在最後。java

Java 7或更低版更低本

當使用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或更高版本

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

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));
}

Google Guava

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));
}

Groovy大招

List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));

        def re = list.findAll {
            it != null
        }

        assert re == ["A", "B"]

有興趣能夠讀讀Groovy中的閉包v8


  • 鄭重聲明:「FunTester」首發,歡迎關注交流,禁止第三方轉載。

技術類文章精選

無代碼文章精選

相關文章
相關標籤/搜索