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


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

拋磚引玉,先拋磚,大招在最后。

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()方法,以幫助我們根據給定的謂詞過濾值。

@Test
public removeNull() {
 
    List<String> list = new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    Iterables.removeIf(list, Predicates.isNull());
 
    assertThat(list, hasSize(2));
}

另外,如果我們不想修改現有列表,Guava允許我們創建一個新的列表:

@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中的閉包


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

技術類文章精選

無代碼文章精選


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM