Java 8 expression fill list from list with another list inside

I'm trying to reach a lambda expression avoiding doing this:

for (OrderEntity o: onEntryL) {
    for(GeoFenceEventEntity g: o.getGeoFenceEvent()){
        if(null != g.getEndAt() && g.getDynamoGeofenceType().equalsIgnoreCase("WAREHOUSE")){
            //all of them, get data
        }
    }
}

And on Lambda trying something like this (with errors):

List<OrderEntity> chargingL = onEntryL.stream()
                              .map(o->o.getGeoFenceEvent().stream()
                              .map(g->null != g.getEndAt() && g.getDynamoGeofenceType().equalsIgnoreCase("WAREHOUSE"))
                              .collect(Collectors.toList()));

Appreciate any help, regards.

Upvotes: 2

Views: 1026

Answers (2)

Adam Millerchip
Adam Millerchip

Reputation: 23091

I think you want flatMap with filter.

onEntryL.stream()
        .map(OrderEntity::getGeoFenceEvent)
        .flatMap(e -> e.stream().filter(g -> null != g.getEndAt() && g.getDynamoGeofenceType().equalsIgnoreCase("WAREHOUSE")))
        .flatMap(g -> g.getData().stream())
        .collect(Collectors.toList());

Upvotes: 1

DCTID
DCTID

Reputation: 1337

OK, update for comment. Assuming you take the OrderEntry if any GeoFenceEventEntity meets your conditions then you can use

List<OrderEntity> chargingL = onEntryL
           .stream()
           .filter(o -> o.getGeoFenceEvent().stream().anyMatch(g -> null != g.getEndAt() && g.getDynamoGeofenceType().equalsIgnoreCase("WAREHOUSE")))
           .collect(Collectors.toList());

Upvotes: 4

Related Questions