Stream filter using Predicate to fetch latest record

Viewed 840

I have a method of type boolean which returns stream of data of Predicate type Incident, I want to filter out the latest incident only.

2 Answers

You have to check all elements in stream. You can collect all filtered elements to LinkedList and get the last one.

forloebs.stream()
.filter(predicate)
.collect(Collectors.toCollection(LinkedList::new)).peekLast();

peekLast will return null if this list is empty.

You can use the max function to get latest incident that matches your completeincident condition.

Optional<Incident> latestIncident = forloebs.stream()
 .filter(completeincident)
 .max(Comparator.comparing(x -> x.getDateIncident()));

The comparator will keep the latest element based on getDateIncident.

It will return Optional.Empty if none of them matches filter criteria.

Related