英文:
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<Segment> segments;
   //.. getter setter 
I try to do so, but it is not compile. What is problem here?
int sum = flightList.forEach(flight -> {
    flight.getSegments().stream().mapToInt(segment -> (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 -> f.getSegments().stream())
              .mapToLong(s -> 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 -> flight.getSegments().stream())
.mapToInt(segment -> (int) ChronoUnit.HOURS.between(segment.getDepartureDate(), segment.getArrivalDate())
.sum();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论