Maxime Maxime - 1 month ago 11
Android Question

Sort list in two differents ways

I have a list of objects that I want to sort by date, with a condition. My aim is to get a list with ascending end_date if end_date is greater or equal than today then a list ordered by descending start_date for objets with end_date in past.

I have a model like that :

public class Trip implements Serializable, Comparable<Trip> {
public int id;
public Calendar date_begin, date_end;
}


and I tried that, but it doesn't work or it's too slow.

@Override
public int compareTo(Trip trip) {
if (date_end.getTimeInMillis() < Calendar.getInstance().getTimeInMillis() &&
trip.date_end.getTimeInMillis() < Calendar.getInstance().getTimeInMillis()) {
return comparePast(trip);
} else if (date_end.getTimeInMillis() > Calendar.getInstance().getTimeInMillis() &&
trip.date_end.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()) {
return compareCurrent(trip);
} else {
return date_end.compareTo(trip.date_end);
}
}


Is there an easyest or fastest way?

Answer

What is making this code so slow is the many calls to Calendar.getInstance(), creating Calendar objects. The code would already be a lot faster if you called this once per compare.

However, it doesn't make much sense to keep creating these in a single sort run. You can either set a static Calendar reference that the sort can use, or use System.currentTimeMillis to get the current time.