如何使用 Stream API 进行求和?

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

How to sum with Stream api?

问题

我试图在每个片段中找到两个日期之间的小时总数。

片段:

class Segment {
    private final LocalDateTime departureDate;

    private final LocalDateTime arrivalDate; 
    //..获取器 设置器  

航班:

class Flight {
    private final List<Segment> segments;
   //.. 获取器 设置器 

我尝试这样做,但无法编译通过。问题在哪里?

int sum = flightList.forEach(flight -> {
    flight.getSegments().stream().mapToInt(segment -> (int) ChronoUnit.HOURS.between(segment.getDepartureDate(), segment.getArrivalDate())).sum();
});
英文:

I'm trying to find the sum of hours between two dates in each segment.

Segment:

class Segment {
    private final LocalDateTime departureDate;

    private final LocalDateTime arrivalDate; 
    //..getter setter  

Flight:

class Flight {
    private final List&lt;Segment&gt; segments;
   //.. getter setter 

I try to do so, but it is not compile. What is problem here?

int sum = flightList.forEach(flight -&gt; {
    flight.getSegments().stream().mapToInt(segment -&gt; (int) ChronoUnit.HOURS.between(segment.getDepartureDate(), segment.getArrivalDate())).sum();
});

答案1

得分: 4

我会将代码部分翻译为中文,如下所示:

long sum =
    flightList.stream()
              .flatMap(f -> f.getSegments().stream())
              .mapToLong(s -> ChronoUnit.HOURS.between(
                                  s.getDepartureDate(), s.getArrivalDate()))
              .sum();
英文:

I'd stream the flightList, then flatMap it to get a list of Segments, and then map them to the hours between departure and arrival and sum. Note that ChronoUnit.between returns a long, not an int though:

long sum = 
    flightList.stream()
              .flatMap(f -&gt; f.getSegments().stream())
              .mapToLong(s -&gt; ChronoUnit.HOURS.between(
                                  s.getDepartureDate(), s.getArrivalDate()))
              .sum();

答案2

得分: 1

.forEach()操作没有返回值,因此您无法将其赋值给sum变量。您在这里需要使用的是flatMap()操作:

flightList.stream().flatMap(flight -> flight.getSegments().stream())
.mapToInt(segment -> (int) ChronoUnit.HOURS.between(segment.getDepartureDate(), segment.getArrivalDate()))
.sum();
英文:

The .forEach() operation does not return anything, so you cannot assign it to the sum variable. What you need here is the flatMap() operation:

flightList.stream().flatMap(flight -&gt; flight.getSegments().stream())
.mapToInt(segment -&gt; (int) ChronoUnit.HOURS.between(segment.getDepartureDate(), segment.getArrivalDate())
.sum();

huangapple
  • 本文由 发表于 2020年9月26日 03:07:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64070076.html
匿名

发表评论

匿名网友

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

确定