2016-12-24 542 views
1

我有四個字符串需要追加。Java/Android:追加多個字符串,如果字符串爲空,則跳過

String food = extras.getString("food"); 
String file = extras.getString("file"); 
String parcel = extras.getString("parcel"); 
String others = extras.getString("others"); 

String itemList = new StringBuilder(food).append("\n") 
         .append(file).append("\n") 
         .append(parcel).append("\n") 
         .append(others).toString(); 

此代碼將prints,如果讓我選擇FoodFile

Food 
File 
null 
null 

由於Parcel和別人有沒有值(這是null),如何使它將打印象下面這樣?

Food 
File 

我試過使用if else但它會太長(14種可能性)。有沒有其他方法可以使其更短,更有效?

+0

什麼是'extras'的類型 –

+0

@PavneetSingh它是一個包 – August

+0

您支持的最低API級別是多少?你是否能夠使用這樣的'String food = extras.getString(「food」,「」);' –

回答

1

的Java 8的流媒體功能提供了這樣的一個非常簡潔的方式:

String itemList = 
    Stream.of(food, file, parcel, others) 
      .filter(Objects::nonNull) 
      .collect(Collectors.joining("\n")); 

編輯:
對於舊版本的Java,你可以做一個傳統的for循環類似的東西,雖然這將是笨重:

StringBuilder sb = new StringBuilder(); 
for (String s : Arrays.asList(food, file, parcel, others)) { 
    if (s != null) { 
     sb.append(s).append('\n'); 
    } 
} 
String itemList = sb.toString(); 
+0

無法解析符號'流'..我想這是因爲Java 8的?但在項目設置中,可能已經設置了jdk1.8.0_101 – August

+0

@八月。我強烈建議將您的JDK/Android版本升級到支持Streams的版本。如果這是不可能的,請參閱我編輯的舊版本的變體答案。 – Mureinik

1

你可以簡單地替換所有null

String food = "food"; 
    String file = "file"; 
    String parcel = null; 
    String others = null; 

    String itemList = new StringBuilder(food).append("\n").append(file).append("\n").append(parcel).append("\n").append(others).toString(); 
    itemList=itemList.replaceAll("\n?null\n?", ""); 
    System.out.println(itemList); 

輸出:

food 
file 

\n?null\n?\n?意味着可以有一個或上null

兩側沒有\n值,使之簡單地用空字符串

1

如果你想替換所有值去Java 8以下,然後通過Java中的Ternary Operator。請參閱下面的代碼片段:

String itemList = new StringBuilder(food!=null?food+"\n":"") 
      .append(file!=null?file+"\n":"") 
      .append(parcel!=null?parcel+"\n":"") 
      .append(others!=null?others+"\n":"") 
      .toString(); 

itemList將有理想的結果。 希望它有幫助。