英文:
converting foreach to filter
问题
我想将代码从这样:
List<FlightPositionRoute> flightPositionRoutes = new ArrayList<>();
dtos.stream()
.map(a -> positions.getPositions(a.getId().getValue()))
.forEach(flightPositionRoute -> flightPositionRoute.ifPresent(flightPositionRoutes::add));
转换为这样:
List<FlightPositionRoute> flightPositionRoutes = dtos.stream()
.map(a -> positions.getPositions(a.getId().getValue()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
我的意思是,我想使用 filter
代替 foreach
,因为它更优雅
不过,很遗憾,我遇到了这个问题:
Required type: List<FlightPositionRoute>
Provided: List<Optional<FlightPositionRoute>>
如何修复这个问题?
英文:
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?
答案1
得分: 2
你只需要解开 Optional
:
List<FlightPositionRoute> flightPositionRoutes = dtos.stream()
.map(a -> positions.getPositions(a.getId().getValue()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
英文:
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());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论