Klaaz0r
Klaaz0r

Reputation: 21

Store overlapping dates from ArrayList

I have a problem comparing dates.

I am working on a parking lot app, there are a X amount of places available and I store an begin date and end date (reservating the parking spot) in sql. My idea is to check from the ArrayList with al the reservations if there is a moment when there are more than x amount of overlapping days.

ArrayList<Reservering> alleReserveringen = reserveringDAO
                .getAlleReservering();
        int totaal = 0;
        for (int i = 0; i < alleReserveringen.size(); i++) {
            for (int j = 0; j < alleReserveringen.size(); j++) {
                if (alleReserveringen.get(i).getVertrek()
                        .before(alleReserveringen.get(j).getAankomst())
                        || alleReserveringen
                                .get(i)
                                .getAankomst()
                                .before(alleReserveringen.get(j)
                                        .getVertrek())) {
                //overlapping
                } else {
                //not overlapping
                }
            }
        }

This is what I did with a nested for loop to compare each date with all the others etc. but this is where I get stuck. Can I store the overlapping dates in someway?

Upvotes: 0

Views: 200

Answers (1)

dimo414
dimo414

Reputation: 48824

This is a perfect use case for Guava's RangeSet, it efficiently stores ranges as start-end pairs, merging overlaps and providing O(log n) contains checks.

There is also RangeMap if you're trying to map start-end pairs to values. There isn't a RangeMultimap currently, unfortunately, but you could create a wrapper easily enough.

Upvotes: 1

Related Questions