Get the last non-null list item using Java 8

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); } } // handling of case when all elements are null // or list is empty ... } 

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(/*handle this case*/); ..... } public Optional<CustomObject> getFirstObject(List<CustomObject> list) { return list.stream().filter(object -> object != null).findFirst(); } 

Can anyone know how to solve this problem?

+7
java lambda java-8 java-stream
source share
1 answer

A possible solution would be to iterate over the list in reverse order and save the first non-empty 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 Stream is not necessarily ordered or finite.

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

 public Optional<CustomObject> getLastObject(List<CustomObject> list) { return list.stream().filter(Objects::nonNull).reduce((a, b) -> b); } 
+10
source share

All Articles