简体   繁体   English

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

[英]Best way to get first not null value using optionals in Java

We have code like this:我们有这样的代码:

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();
    }
}

I want to remove brackets, so if it was only 2 values I'd write like this:我想删除括号,所以如果它只有 2 个值,我会这样写:

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

But is there any way to write such chain for 3+ values?(withount using second optional in orElse call)但是有没有办法为 3+ 个值编写这样的链?(在 orElse 调用中不使用第二个可选)

Since your second option is actually a property, you can rely on the getProperty(String, String) method rather than just getProperty(String) :由于您的第二个选项实际上是一个属性,您可以依赖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());

Though I'd recommend using Path rather than File in that latter part ( Paths.get(System.getProperty("java.io.tmpdir")).toURI().toString() )尽管我建议在后一部分中使用Path而不是FilePaths.get(System.getProperty("java.io.tmpdir")).toURI().toString()

You could use an ordered List and pick the first non-null item from it.您可以使用有序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"

Try this.尝试这个。

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

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM