[英]Is it possible to return first not null value for different Java types with Optionals?
[英]Best way to get first not null value using optionals in 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 調用中不使用第二個可選)
由於您的第二個選項實際上是一個屬性,您可以依賴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()
)
您可以使用有序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"
嘗試這個。
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.