-2

I would like to convert

List<FlightPositionRoute> flightPositionRoutes = new ArrayList<>();

            dtos.stream()
                    .map(a-> positions.getPositions(a.getId()
                            .getValue()))
                    .forEach(flightPositionRoute -> 
                               flightPositionRoute.ifPresent(flightPositionRoutes::add));

To this:

List<FlightPositionRoute> flightPositionRoutes = dtos.stream()
                    .map(a-> positions.getPositions(a.getId()
                            .getValue()))
                    .filter(Optional::isPresent)
                    .collect(Collectors.toList());

I mean I would like to use filter instead of foreach, because it's prettier ;)

Unfortunately, I'm getting

Required type: List <FlightPositionRoute>
Provided: List <Optional<FlightPositionRoute>>

How can I repair it?

Eklavya
  • 17,618
  • 4
  • 28
  • 57
pqa1222
  • 75
  • 1
  • 8
  • `....filter(Optional::isPresent).map( e -> e.get())...` – Eklavya Oct 07 '20 at 18:17
  • `flatMap` by `Optional:stream` should be enough: `dtos.stream().map(a-> positions.getPositions(a.getId().getValue())).flatMap(Optional::stream).collect(Collectors.toList());` will provide `List` – Nowhere Man Oct 07 '20 at 19:25

1 Answers1

2

You just need to unpack the Optional:

List<FlightPositionRoute> flightPositionRoutes = dtos.stream()
    .map(a-> positions.getPositions(a.getId().getValue()))
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(Collectors.toList());
Polygnome
  • 7,639
  • 2
  • 37
  • 57