繁体   English   中英

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

[英]JAVA 8 Stream filter using Predicate to fetch latest record

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

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

我试过了

return f != null && f.stream().filter(predicate)

有点像这样,但我想从方法 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);
    }

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

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

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

您可以通过Max function 获取与您的completeincident事件条件相匹配的最新事件。

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

比较器将根据getDateIncident保留最新的元素。

如果它们都不符合过滤条件,它将返回Optional.Empty

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM