gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:27:12 28 4
gpt4 key购买 nike

我们有这样的代码:

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

最佳答案

由于您的第二个选项实际上是一个属性,因此您可以依赖 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())

关于java - 在 Java 中使用可选值获取第一个非空值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36662621/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com