Reputation: 1600
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:
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)
Upvotes: 1
Views: 741
Reputation:
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());
Upvotes: 0
Reputation: 34618
Since your second option is actually a property, you can rely on the getProperty(String, String)
method rather than just 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()
)
Upvotes: 2
Reputation: 24802
You could use an ordered List
and pick the first non-null item from it.
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"
Upvotes: 0