What is the best Java equivalent of Javascript OR?

In Javascript, I can do the following to get the value according to their order of occurrence in the assignment ..

var myString = source1 || source2 || source3 || source4 || source5;

If any of the sources matters, it will be assigned to myString. If all sources matter, he will be the first.

In Java, java.util.Optionalit seems limited just in time Optional.of("value").orElse( "another" ), and it can no longer be hooked, since the return of orElse () is already a string.

+4
source share
3 answers

I would probably use something simple:

public static <T> T first(T... values) {
    for (T v : values) {
        if (v != null) return v;
    }
    return null;
}
+6
source

Although it can be argued that there are many 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);
+4
source

api

, , , lambdas .., .

You can use three dots ...to indicate "any number of arguments," which in your method will effectively turn intoString[] arguments

Then repeat them and compare with the custom comparison function. In this case, I decided to emulate javascript with non-zero lines, not empty lines. Change as you see fit.

public String sourceFilter(String... input) {
    for(String test : input) {
        if(test != null && !test.isEmpty()) {
            return test;
        }
    }
    return "";
}

I don’t know that the breakeven point is that threads are more efficient in this case, but I would suggest that it would be a fairly large number to cover the initialization cost for it.

+2
source

Source: https://habr.com/ru/post/1695142/


All Articles