In Java 7, if I want to get the last non-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); } }
I want to write shorter code using lambdas or another Java 8 function. For example, if I want to get the first non-zero element, I can write this:
public void someMethod(List<CustomObject> list) { ..... CustomObject object = getFirstObject(list).orElseGet(); ..... } public Optional<CustomObject> getFirstObject(List<CustomObject> list) { return list.stream().filter(object -> object != null).findFirst(); }
Can anyone know how to solve this problem?
java lambda java-8 java-stream
ZhenyaM
source share