In Javascript I can do the following to get a value according to their respective order of appearance in the assignment..
var myString = source1 || source2 || source3 || source4 || source5;
If any of the sources has value, it will be assigned to myString. If all sources have value, it will take the first one.
In Java, the java.util.Optional
seems limited to only just Optional.of("value").orElse( "another" )
and it cannot chain anymore as the the return of orElse() is already a string.
I would probably use something simple like:
public static <T> T first(T... values) {
for (T v : values) {
if (v != null) return v;
}
return null;
}
While it can be argued that there are lot of approaches, I prefer the following approach:
Integer i = Stream.of(null, null, null, null, null, null, null, null, 1, 2)
.filter(Objects::nonNull) // filter out null's
.findFirst().orElse(10); // default to 10
// Objects::nonNull is same as e -> e != null
System.out.println(i);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With