简体   繁体   English

过滤收集问题,使用 Stream API

[英]Problem with filtering collection, using Stream API

I try to filter collection of objects that have collection field, using Stream API:我尝试使用 Stream API 过滤具有集合字段的对象集合:

@Override
public void method (List<Flight> flightList) 
{
List<Flight> trueFlights = flightList.forEach(flight -> flight.getSegments().stream().filter(segment -> segment.getArrivalDate().isBefore(segment.getDepartureDate())).collect(Collectors.toList()));
return trueFlights;
}

But it does not compile:但它不编译:

Error:(32, 27) java: incompatible types: void cannot be converted to java.util.List错误:(32, 27) java:不兼容的类型:void 不能转换为 java.util.List

Segment:部分:

class Segment {
    private final LocalDateTime departureDate;

    private final LocalDateTime arrivalDate; 
    //..getter setter  

Flight:航班:

class Flight {
    private final List<Segment> segments;
   //.. getter setter 

What am I doing wrong?我究竟做错了什么?

You could be looking for filter operation over a Stream .您可能正在寻找对Stream filter操作。 That would further require you to include a predicate, which is possible with the use of terminal operations anyMatch , allMatch over the inner stream.这将进一步要求您包含一个谓词,这可以通过对内部流使用终端操作anyMatchallMatch来实现。

For example, if you want to include input flights to trueFlights if any of its segment satisfies the condition that the arrival date is before departure date, you could perform anyMatch :例如,如果您想将输入航班包含到trueFlights如果其任何段满足到达日期早于出发日期的条件,您可以执行anyMatch

List<Flight> trueFlights = flightList.stream()
        .filter(flight -> flight.getSegments().stream()
                .anyMatch(segment -> segment.getArrivalDate().isBefore(segment.getDepartureDate())))
        .collect(Collectors.toList());

What you did incorrectly on the other hand was to make use of forEach which has a void return type and then trying to collect elements further from it.另一方面,您forEach是使用具有void返回类型的forEach ,然后尝试从中进一步收集元素。

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

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