Skip to content
Advertisement

Using Stream API to count stats

I have following model representing a Snack bar SnackBarStat – This has a start date for a booking, number of customers in booking and number of Days(customer can set a start date and say for how many days they want to have table)

JavaScript

Now given a list of such stats I am trying to find for each date how many customer are there in snack bar

For example if input is

JavaScript

Expected output is

JavaScript

What I have tried so far. I have created a simple logic to iterate over each startDate, expand the dates based on numberOfDays and then for each date add them to a map with summing customers on that date

JavaScript

This code works. I was wondering if there was shorter way with stream api to do the same. Note the code is just for demo purpose and I have made use of better code practice in actual code.

Advertisement

Answer

You can use flatMap to “expand” the dates, and then you can use groupingBy to group the expanded dates:

JavaScript

Though this is shorter, note that it is probably slower than your loops.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement