2016-04-16 4 views
1

でoptionalsを使用して最初のないnull値を取得しますベストな方法は、我々はこのようなコードを持っているJavaの

String tempDir = SwingInstanceManager.getInstance().getTempFolderPath(clientId); 
if (tempDir == null) { 
    tempDir = System.getProperty(Constants.TEMP_DIR_PATH); 
    if (tempDir == null) { 
      tempDir = new File(System.getProperty("java.io.tmpdir")).toURI().toString(); 
    } 
} 

それは私がこのように記述しますのみ2値だったので、もし私は、括弧を削除する:

String tempDir = Optional.ofNullable(SwingInstanceManager.getInstance().getTempFolderPath(clientId)).orElse(System.getProperty(Constants.TEMP_DIR_PATH)); 

しかし3+値のため、このようなチェーンを書くには?(orElse呼び出しで2番目のオプションを使用してwithount)

答えて

1

、あなたはgetProperty(String, String)方法に頼ることができるだけではなく、getProperty(String)

String tempDir = Optional.ofNullable(SwingInstanceManager.getInstance().getTempFolderPath(clientId)) 
         .orElse(System.getProperty(Constants.TEMP_DIR_PATH, 
                new File(System.getProperty("java.io.tmpdir")).toURI().toString()); 

私はその後半にPathではなくFileを使用することをお勧めしたいけど( Paths.get(System.getProperty("java.io.tmpdir")).toURI().toString()

0

はあなたが注文したListを使用してから最初のnull以外の項目を選ぶことができどのような方法があります それ。あなたの目のオプションは、プロパティが実際にあるので

String[] tempSourcesArray = {null, "firstNonNull", null, "otherNonNull"}; 
List<String> tempSourcesList = Arrays.asList(tempSourcesArray); 
Optional firstNonNullIfAny = tempSourcesList.stream().filter(i -> i != null).findFirst(); 
System.out.println(firstNonNullIfAny.get()); // displays "firstNonNull" 
+0

それがコードの量を増加させ、代わりにそれを減少させる:( – maxpovver

+0

まあ、本当にそれが(ちょうど1行 'list.streamです)。フィルタリング(I =>私!= null).findFirst() '残りはここにあるのでスタンドアローンとして動作します。 – Aaron

0

これを試してください。

public static <T> T firstNotNull(Supplier<T>... values) { 
    for (Supplier<T> e : values) { 
     T value = e.get(); 
     if (value != null) 
      return value; 
    } 
    return null; 
} 

String tempDir = firstNotNull(
    () -> SwingInstanceManager.getInstance().getTempFolderPath(clientId), 
    () -> System.getProperty(Constants.TEMP_DIR_PATH), 
    () -> new File(System.getProperty("java.io.tmpdir")).toURI().toString()); 
関連する問題