Issue
I have the following TicketDTO Object:
public class TicketDTO {
private LocalDate date;
private Set<OffenceDTO> offences;
}
And every OffenceDTO has an int field - penalty points.
public class OffenceDTO {
private int penaltyPoints;
}
I would like to add up the penalty points to a single int value by streaming the Set of Offenses of each Ticket. But only if the ticket's date is between the last two years.
I have collected tickets from the last two years, but now I have a problem in how to go through the offenses and count their points.
This is what I've written so far:
tickets().stream()
.filter(ticketEntity -> isDateBetween(LocalDate.now(), ticketEntity.getDate()))
.collect(Collectors.toList());
Solution
I would like to collect the penalty points in a single
intvalue by streaming the set of tickets
It can be done in the following steps:
- Turn the stream of filtered tickets into a stream of
OffenceDTOusingflatMap(); - Extract penalty points from
OffenceDTOwithmapToInt(), that will transform a stream of objects into aIntStream; - Apply
sum()to get the total.
int totalPenalty = tickets().stream()
.filter(ticketEntity -> isDateBetween(LocalDate.now(), ticketEntity.getDate()))
.flatMap(ticketDTO -> ticketDTO.getOffences().stream())
.mapToInt(OffenceDTO::getPenaltyPoints)
.sum();
Answered By - Alexander Ivanchenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.