将foreach转换为filter

huangapple go评论76阅读模式
英文:

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,因为它更优雅 将foreach转换为filter

不过,很遗憾,我遇到了这个问题:

Required type: List<FlightPositionRoute>
Provided: List<Optional<FlightPositionRoute>>
如何修复这个问题?
英文:

I would like to convert

List&lt;FlightPositionRoute&gt; flightPositionRoutes = new ArrayList&lt;&gt;();

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

To this:

List&lt;FlightPositionRoute&gt; flightPositionRoutes = dtos.stream()
                    .map(a-&gt; 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 将foreach转换为filter

Unfortunately, I'm getting

Required type: List &lt;FlightPositionRoute&gt;
Provided: List &lt;Optional&lt;FlightPositionRoute&gt;&gt;

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&lt;FlightPositionRoute&gt; flightPositionRoutes = dtos.stream()
    .map(a-&gt; positions.getPositions(a.getId().getValue()))
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年10月8日 02:13:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64249992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定