maxpovver
maxpovver

Reputation: 1600

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:

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

Answers (3)

user4910279
user4910279

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

RealSkeptic
RealSkeptic

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

Aaron
Aaron

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

Related Questions