2017-07-06 65 views
0

我的問題是集合有一個空值,並且任何「utils」方法返回該集合不是空的。還有其他「優雅」選項?使用空元素驗證空集合

此代碼拋出一個空指針異常:

public static void main(String[] args) { 
    ArrayList<String> strings = new ArrayList<>(); 
    strings.add(null); 

    if(CollectionUtils.isNotEmpty(strings)) { 
     for (String s : strings) { 
      System.out.println(s.length()); 
     } 
    } 
} 
+0

歡迎堆棧溢出!尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須在問題本身中包含所需的行爲,特定的問題或錯誤以及必要的最短代碼**。沒有明確問題陳述的問題對其他讀者無益。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

+4

包含null _isn't_ empty的集合。如果你的集合可以包含null,你需要在迭代時檢查它。 (但99%的時間你最好只是讓你的收藏包含空值不可能) –

+0

這不是https://stackoverflow.com/questions/34305512/what-is-difference-在null和empty-list之間 - 這裏的OP是要求「是否有一個用於檢測列表是否包含null的util方法?」。 –

回答

1

您可以檢查是否有集合中的空值和/或過濾像下面的代碼:

public static void main(String[] args) { 
    List<String> strings = new ArrayList<>(); 
    strings.add("one"); 
    strings.add(null); 
    strings.add("two"); 

    // has a null value? 
    final boolean hasNulls = strings.stream() 
      .anyMatch(Objects::isNull); 
    System.out.println("has nulls: " + hasNulls); 

    // filter null values 
    strings = strings.stream() 
      .filter(Objects::nonNull) 
      .collect(Collectors.toList()); 

    System.out.println("filtered: " + strings.toString()); 
} 
+0

OP不知道如何做一個空檢查,你顯示他流處理? –

+0

@AhhijitSarkar:他正在尋求優雅的選項來檢查或處理可能包含空值的收藏。當然,你可以堅持使用for循環,並添加一個額外的'if(s!= null)' –

+0

他有引號中的「優雅」。 –