Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java's best equivalent to Javascript's OR?

Tags:

java

java-8

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.

like image 533
supertonsky Avatar asked Dec 13 '22 17:12

supertonsky


2 Answers

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;
}
like image 183
OldCurmudgeon Avatar answered Dec 16 '22 06:12

OldCurmudgeon


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);
like image 28
Aniket Sahrawat Avatar answered Dec 16 '22 06:12

Aniket Sahrawat