How to Get the First Non-Null Value in Java

How to get the first non-null value in Java?

No, there isn't.

The closest you can get is:

public static <T> T coalesce(T ...items) {
for(T i : items) if(i != null) return i;
return null;
}

For efficient reasons, you can handle the common cases as follows:

public static <T> T coalesce(T a, T b) {
return a == null ? b : a;
}
public static <T> T coalesce(T a, T b, T c) {
return a != null ? a : (b != null ? b : c);
}
public static <T> T coalesce(T a, T b, T c, T d) {
return ...
}

How do I access the first non null term of a List in Java?

If you know that only one p passes the test, I don't know what the point of creating a list with a load of null values plus p is.

Your problem seems to stem from wanting to use forEach. In my opinion, you should almost always use a for loop in preference to forEach. With a simple for loop you can just use break when the item is found.

In detail:

Instance p = null;
for (Instance q : instances) {
if (q.i == i) {
p = q;
break;
}
}
if (p == null)
throw new IllegalStateException(); // It wasn't there.
// Do something with p.

Is there an elegant way to get the first non null value of multiple method returns in Java?

It depends on some factors you are not defining. Do you have a fixed, rather small set of query…Source actions as shown in your question or are you rather heading to having a more flexible, extensible list of actions?

In the first case you might consider changing the query…Source methods to return an Optional<SomeObject> rather than SomeObject or null. If you change your methods to be like

Optional<SomeObject> queryFirstSource(Arguments args) {

}

You can chain them this way:

public SomeObject findSomeObject(Arguments args) {
return queryFirstSource(args).orElseGet(
()->querySecondSource(args).orElseGet(
()->queryThirdSource(args).orElse(null)));
}

If you can’t change them or prefer them to return null you can still use the Optional class:

public SomeObject findSomeObject(Arguments args) {
return Optional.ofNullable(queryFirstSource(args)).orElseGet(
()->Optional.ofNullable(querySecondSource(args)).orElseGet(
()->queryThirdSource(args)));
}

If you are looking for a more flexible way for a bigger number of possible queries, it is unavoidable to convert them to some kind of list or stream of Functions. One possible solution is:

public SomeObject findSomeObject(Arguments args) {
return Stream.<Function<Arguments,SomeObject>>of(
this::queryFirstSource, this::querySecondSource, this::queryThirdSource
).map(f->f.apply(args)).filter(Objects::nonNull).findFirst().orElse(null);
}

This performs the desired operation, however, it will compose the necessary action every time you invoke the method. If you want to invoke this method more often, you may consider composing an operation which you can re-use:

Function<Arguments, SomeObject> find = Stream.<Function<Arguments,SomeObject>>of(
this::queryFirstSource, this::querySecondSource, this::queryThirdSource
).reduce(a->null,(f,g)->a->Optional.ofNullable(f.apply(a)).orElseGet(()->g.apply(a)));

public SomeObject findSomeObject(Arguments args) {
return find.apply(args);
}

So you see, there are more than one way. And it depends on the actual task what direction to go. Sometimes, even the simple if sequence might be appropriate.

BigQuery Standard Get first not null value when grouping

Below is for BigQuery Standard SQL

#standardSQL
SELECT AS VALUE ARRAY_AGG(t ORDER BY IF(DIMENSION IS NULL, NULL, DATE_SALES) DESC LIMIT 1)[OFFSET(0)]
FROM `project.dataset.table` t
GROUP BY CUSTOMERS_ID

if to apply to sample data from your question - result is

Row CUSTOMERS_ID    DATE_SALES  DIMENSION    
1 MARIO1 20200113 Spain
2 MARIO2 20200131 null
3 MARIO3 20200101 France

How to get index of the first not null array element?

One trick is to create a stream of indexes, and then find the first one that points to a non-null value:

int index =
IntStream.range(0, arr.length)
.filter(i -> arr[i] != null)
.findFirst()
.orElse(-1 /* Or some other default */);


Related Topics



Leave a reply



Submit