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?