-1

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();
});
petrov.aleksandr
  • 622
  • 1
  • 5
  • 24
  • 3
    Shouldn't that `int sum = ` go _inside_ the loop? `forEach()` returns `void` and thus this can't compile. Also you probably want a sum per flight, right? – Thomas Sep 25 '20 at 19:09
  • 2
    Does this answer your question? [How to sum values in a Map with a stream?](https://stackoverflow.com/questions/30089469/how-to-sum-values-in-a-map-with-a-stream) – Kars Sep 25 '20 at 19:12

2 Answers2

4

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();
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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();
Utku Özdemir
  • 7,390
  • 2
  • 52
  • 49