JAVA 8 Stream 过滤器使用 Predicate 获取最新记录

Shu*_*jee 6 java lambda predicate java-8 java-stream

我有一个布尔类型的方法,它返回谓词类型事件的数据流,我只想过滤掉最新的事件。

public boolean hascompletededucation(LocalDate asOnDate) {
        Predicate<Courses> predicate = e -> ((e.hasincident1(asOnDate));
        return f != null && f.stream().anyMatch(predicate);         
Run Code Online (Sandbox Code Playgroud)

我试过

return f != null && f.stream().filter(predicate)
Run Code Online (Sandbox Code Playgroud)

有点像这样,但我想从方法 hasincident1 中获取最新事件。

方法 hasincident1 如下:

public boolean hasincident1(LocalDate asOnDate) {
        Predicate<Incident> completeincident= e -> !e.isCancelled() && e.isCompleted()
                && (e.getDate().toLocalDate().isBefore(asOnDate)
                        || e.getDateIncident().toLocalDate().isEqual(asOnDate));
        return incidentList != null && incidentList.stream().anyMatch(completeincident);
    }
Run Code Online (Sandbox Code Playgroud)

lcz*_*ski 3

您必须检查流中的所有元素。您可以收集所有过滤元素LinkedList并获取最后一个。

forloebs.stream()
.filter(predicate)
.collect(Collectors.toCollection(LinkedList::new)).peekLast();
Run Code Online (Sandbox Code Playgroud)

null如果此列表为空,peekLast将返回。