Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first non-null value

I have a number of functions:

String first(){}
String second(){}
...
String default(){}

Each can return a null value, except the default. each function can take different parameters. For example, first could take no arguments, second could take in a String, third could take three arguments, etc. What I'd like to do is something like:

ObjectUtils.firstNonNull(first(), second(), ..., default());

The problem is that because of the function call, this does eager evaluation. Where'd I'd like to exit early, say after the second function (because the function calls can be expensive, think API calls, etc). In other languages, you can do something similar to this:

return first() || second() || ... || default()

In Java, I know I can do something like:

String value;
if (value = first()) == null || (value = second()) == null ...
return value;

That's not very readable IMO because of all the == null checks.ObjectUtils.firstNonNull() creates a collection first, and then iterates, which is okay as long as the function gets evaluated lazily.

Suggestions? (besides doing a bunch of ifs)

like image 967
lorenzocastillo Avatar asked Apr 07 '17 14:04

lorenzocastillo


People also ask

How do I return the first non-null value in SQL?

SQL COALESCE – a function that returns the first defined, i.e. non-NULL value from its argument list. Usually one or more COALESCE function arguments is the column of the table the query is addressed to. Often a subquery is also an argument for a function.

Which function returns first not null?

COALESCE returns the first non-null expr in the expression list. At least one expr must not be the literal NULL . If all occurrences of expr evaluate to null, then the function returns null.

Does First value ignore nulls?

If the first value in the set is null, the function returns NULL unless you specify IGNORE NULLS. If you specify IGNORE NULLS, FIRST_VALUE returns the first non-null value in the set, or NULL if all values are null. Returns the last value in an ordered set of values.

Which function returns the value of the non-null value?

The SQL Coalesce function evaluates the arguments in order and always returns first non-null value from the defined argument list.


Video Answer


3 Answers

String s = Stream.<Supplier<String>>of(this::first, this::second /*, ... */)
                 .map(Supplier::get)
                 .filter(Objects::nonNull)
                 .findFirst()
                 .orElseGet(this::defaultOne);

It stops on the first non-null value or else sets the value which is returned from defaultOne. As long as you stay sequential, you are safe. Of course this requires Java 8 or later.

The reason why it stops on the first occurrence of a non-null value is due how the Stream handles each step. The map is an intermediate operation, so is filter. The findFirst on the other side is a short-circuiting terminal operation. So it continues with the next element until one matches the filter. If no element matches an empty optional is returned and so the orElseGet-supplier is called.

this::first, etc. are just method references. If they are static replace it with YourClassName::first, etc.

Here is an example if the signature of your methods would differ:

String s = Stream.<Supplier<String>>of(() -> first("takesOneArgument"),
                                       () -> second("takes", 3, "arguments")
                                   /*, ... */)
                 .map(Supplier::get)
                 .filter(Objects::nonNull)
                 .findFirst()
                 .orElseGet(this::defaultOne);

Note that the Supplier is only evaluated when you call get on it. That way you get your lazy evaluation behaviour. The method-parameters within your supplier-lambda-expression must be final or effectively final.

like image 140
Roland Avatar answered Oct 22 '22 03:10

Roland


This can be done pretty cleanly with a stream of Suppliers.

Optional<String> result = Stream.<Supplier<String>> of(
     () -> first(), 
     () -> second(),
     () -> third() )
  .map( x -> x.get() )
  .filter( s -> s != null)
  .findFirst(); 

The reason this works is that despite appearances, the whole execution is driven by findFirst(), which pulls an item from filter(), which lazily pulls items from map(), which calls get() to handle each pull. findFirst() will stop pulling from the stream when one item has passed the filter, so subsequent suppliers will not have get() called.

Although I personally find the declarative Stream style cleaner and more expressive, you don't have to use Stream to work with Suppliers if you don't like the style:

Optional<String> firstNonNull(List<Supplier<String>> suppliers {
    for(Supplier<String> supplier : suppliers) {
        String s = supplier.get();
        if(s != null) {
            return Optional.of(s);
        }
    }
    return Optional.empty();
}

It should be obvious how instead of returning Optional you could equally return a String, either returning null (yuk), a default string, or throwing an exception, if you exhaust options from the list.

like image 10
slim Avatar answered Oct 22 '22 05:10

slim


It isn't readable because you are dealing with a bunch of separate functions that don't express any kind of connection with each other. When you attempt to put them together, the lack of direction is apparent.

Instead try

 public String getFirstValue() {
      String value;
      value = first();
      if (value != null) return value;
      value = second();
      if (value != null) return value;
      value = third();
      if (value != null) return value;
      ...
      return value;
 }

Will it be long? Probably. But you are applying code on top of a interface that's not friendly toward your approach.

Now, if you could change the interface, you might make the interface more friendly. A possible example would be to have the steps be "ValueProvider" objects.

public interface ValueProvider {
    public String getValue();
}

And then you could use it like

public String getFirstValue(List<ValueProvider> providers) {
    String value;
    for (ValueProvider provider : providers) {
       value = provider.getValue();
       if (value != null) return value;
    }
    return null;
}

And there are various other approaches, but they require restructuring the code to be more object-oriented. Remember, just because Java is an Object-Oriented programming language, that doesn't mean it will always be used in an Object-Oriented manner. The first()...last() method listing is very not-object oriented, because it doesn't model a List. Even though the method names are expressive, a List has methods on it which permit easy integration with tools like for loops and Iterators.

like image 3
Edwin Buck Avatar answered Oct 22 '22 05:10

Edwin Buck