使用Java中的选项获得第一个非空值的最佳方法

时间:2016-04-16 09:52:52

标签: java optional

我们有这样的代码:

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调用中使用第二个可选项)

3 个答案:

答案 0 :(得分: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而不是FilePaths.get(System.getProperty("java.io.tmpdir")).toURI().toString()

答案 1 :(得分:0)

您可以使用有序的List并从中选择第一个非空项目。

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"

答案 2 :(得分: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());