Dadonis
Dadonis

Reputation: 87

JAVA getting all date period

I have a function which takes all period of Trip which can contain flight trips, car trips and expenses like taxi and so on, and they all have dates. I want to return all range of these travels for example if i have travel with start at 2017-01-02 and end at 2017-01-10 and car trip date is 2017-02-01 return date range should be 2017-01-02 and 2017-02-01.

public DateRange updateClaimDates(Claim claim) {
        DateRange dates = new DateRange();
        if (!claim.getFlights().isEmpty()) {
            List<Flight> sortedFlights = Lambda.sort(claim.getFlights(), Lambda.on(Flight.class).getStartDate());
            dates.setStartDate(sortedFlights.get(0).getStartDate());
            dates.setEndDate(sortedFlights.get(sortedFlights.size() - 1).getEndDate());
        } 
        if (!claim.getCarTrips().isEmpty()) {
            List<CarTrip> carTrips = Lambda.sort(claim.getCarTrips(), Lambda.on(CarTrip.class).getTripDate());
            dates.setStartDate(carTrips.get(0).getTripDate().before(dates.getStartDate()) ? carTrips.get(0).getTripDate() : dates.getStartDate());
            dates.setEndDate(carTrips.get(carTrips.size() - 1).getTripDate().after(dates.getEndDate()) ? carTrips.get(carTrips.size() - 1).getTripDate() : dates.getEndDate());
        } 
        if (!claim.getExpenses().isEmpty()) {
            List<Expense> sortedExpenses = Lambda.sort(claim.getExpenses(), Lambda.on(Expense.class).getDate());
            dates.setStartDate(sortedExpenses.get(0).getDate().before(dates.getStartDate()) ? sortedExpenses.get(0).getDate() : dates.getStartDate());
            dates.setEndDate(sortedExpenses.get(sortedExpenses.size() - 1).getDate().after(dates.getEndDate()) ? sortedExpenses.get(sortedExpenses.size() - 1).getDate() : dates.getEndDate());
        }

        return dates;
    }

What would be the most efficient way without having three if statements and this date checking after and before?

Upvotes: 0

Views: 134

Answers (1)

ahoxha
ahoxha

Reputation: 1938

You don't have to sort the lists to find the range. Finding only the minimum/maximum is much more efficient (O(n)) compared to the best case of comparison sorting O(n*lg(n)) or worst case O(n*n).

First, find the three minimums and then get the smallest of those three. Then find the three maximums and get the largest of those three.

Finally, the range will be from the smallest of the three minimums to the largest of the three maximums.

EDIT: Finding the max and min at the same time using the minimum number of comparisons

This answer explains how to find min and max using the minimum number of comparisons, which will further enhance your solution.

Upvotes: 1

Related Questions