Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last not null element of list by using Java 8

In Java 7, if I want to get the last not null element of a list, I write something like this:

public CustomObject getLastObject(List<CustomObject> list) {
    for (int index = list.size() - 1; index > 0; index--) {
        if (list.get(index) != null) {
            return list.get(index);
        }
    }
    // handling of case when all elements are null
    // or list is empty
    ...
}

I want to write a shorter code by using lambdas or another feature of Java 8. For example, if I want to get the first not null element I can write this:

public void someMethod(List<CustomObject> list) {
    .....
    CustomObject object = getFirstObject(list).orElseGet(/*handle this case*/);
    .....
}

public Optional<CustomObject> getFirstObject(List<CustomObject> list) {
    return list.stream().filter(object -> object != null).findFirst();
}

Maybe someone know how to solve this problem?

like image 385
ZhenyaM Avatar asked Sep 18 '15 12:09

ZhenyaM


1 Answers

A possible solution would be to iterate over the List in reverse order and keep the first non null element:

public Optional<CustomObject> getLastObject(List<CustomObject> list) {
    return IntStream.range(0, list.size()).mapToObj(i -> list.get(list.size() - i - 1))
                                          .filter(Objects::nonNull)
                                          .findFirst();
}

Note that there is no findLast method in the Stream API because a Stream is not necessarily ordered or finite.

Another solution is to iterate over the list and reduce it by keeping only the current element. This effectively reduces the Stream to the last element.

public Optional<CustomObject> getLastObject(List<CustomObject> list) {
    return list.stream().filter(Objects::nonNull).reduce((a, b) -> b);
}
like image 185
Tunaki Avatar answered Oct 17 '22 07:10

Tunaki