KuRuVI
KuRuVI

Reputation: 245

Problem to get a map with interval of date as key

I have a list of ballon. A ballon have a fields dateCreation and color. And I have two dates called dateStart and dateEnd that the user chose.

I need to have a Map where the key are all the date between dateStart and dateEnf, and where the value depend of the date of the ballon.

For exemple :

I want to have this map
<2019-01-01, [b1]>
<2019-01-02, [b2]>
<2019-01-03, []>
<2019-01-04 [b3, b4]>
<2019-01-05, []>

For the moment I have this methode

public Map<Date, Ballon[]> getMapOfBallonByDate(Date dateStart, Date dateEnd) {
        List<Ballon> allBallonInTheDateInterval = ticketRepository.findTicketByDate(dateStart, dateEnd);
        ...
        return ...
}

I don't know what to write in the body of the function. Thank you in advance for your help.

Upvotes: 0

Views: 397

Answers (1)

VaibS
VaibS

Reputation: 1893

Map<Date, List<Balloon>> allBalloonInTheDateInterval = ticketRepository.findTicketByDate(dateStart, dateEnd)
.stream()
.collect(groupingBy(Balloon::getDateCreation));

Create a new map Map<Date, Balloon[]> balloonMap = new HashMap<>();

Then you can iterate over the date range. Refer: https://stackoverflow.com/a/4535239/7155432

In each iteration,

Balloon[] currentBalloons = allBalloonInTheDateInterval1.getOrDefault(currentIterationDate, new ArrayList<>()).toArray(new Balloon[0]);
balloonMap.put(currentIterationDate, currentBalloons);

Upvotes: 1

Related Questions