简体   繁体   中英

Sorting objects of ArrayList by their date and time

I have 10 objects in an ArrayList with Patient ID and Appointment date as instance variables. How do I sort the patients by the appointment date?

For some reason I am unable to use a Comparator to sort the ArrayList ; the compiler gives an error:

java.util.Comparator is abstract; cannot be instantiated

Collections.sort() does not work for Object when not using Comparator .

ArrayList<Appointment> testApp = new ArrayList<>();

while (!App.isEmpty()) {
    tempA = (Appointment) App.dequeue();

    if (tempA.getPatID().equals(search)) {
        testApp.add(tempA);
    }

    tempApp.enqueue(tempA);
}

while (!tempApp.isEmpty()) {
    tempA = (Appointment) tempApp.dequeue();
    App.enqueue(tempA);
}

Collections.sort(testApp, new Comparator<Appointment>());

I'm assuming your Appointment class looks something like this:

class Appointment {
    private int patientId;
    private LocalDateTime appointmentDate;

    // Getters & setters
}

If so, you'd create a Comparator to sort using the Comparator.comparing method:

ArrayList<Appointment> appointments = new ArrayList<>();

Collections.sort(appointments, Comparator.comparing(appointment -> {
    return appointment.getAppointmentDate();
}));

That lambda function tells the comparator how to take your object (an Appointment ) and extract the element used to sort (the key; appointmentDate ). It can be condensed down to a method reference if you like:

Collections.sort(appointments, Comparator.comparing(Appointment::getAppointmentDate));

You can also call Collection#sort() directly on the ArrayList :

appointments.sort(Comparator.comparing(Appointment::getAppointmentDate));

If you're always (or usually) going to sort your Appointment objects by date, you might consider making Appointment implement Comparable so that you can call .sort() without passing a Comparator :

class Appointment implements Comparable<Appointment> {
    private int patientId;
    private LocalDateTime appointmentDate;

    // Getters & setters

    @Override
    public int compareTo(final Appointment other) {
        return appointmentDate.compareTo(other.appointmentDate);
    }
}

to make your class instances be comparable with each other, your class most implements 'Comparable' interface . for example if you have a class named C1 and you want to make C1 instances be comparable, you most declare C1 in following manner :

public class C1 implements Comparable<C1>{
//some codes

@Override
public int compareTo(C1 other){
// here you can compare this instance of C1 (references with this keyword) with other

}

}

now if you use Collections.sort() , your arrayList will be sort

private static final Comparator<Appointment> SORT_BY_DATE_DESC = Comparator.comparing(Appointment::getDate).reversed();

public static void main(String... args) {
    List<Appointment> appointments = Collections.emptyList();
    appointments.sort(SORT_BY_DATE_DESC);
}

public static class Appointment {
    private Date date;

    public Date getDate() {
        return date;
    }
}

You cannot instantiate a Comparator directly, you need to implement the logic yourself, list this

    Comparator<Appointment> comp = new Comparator<>() {
        public int compare(Appointment a1, Appointment a2) {
            // Logic to compare here, see javadoc of that method
            return 0;
        }
    }

    testApp.sort(comp);

Using lambda expression, you can write the code like that:

    testApp.sort((a1, a2) -> {
        // Logic to compare here, see javadoc of that method
        return 0;
    });

If Appointment is a class you have written yourself, you can make it implement Comparable<Appointment> :

class Appointment implements Comparable<Appointment> {
        public int compareTo(Appointment a2) {
            // Logic to compare here, see javadoc of that method
            return 0;
        }
}

This means you can sort your list without specifying a comparator:

    testApp.sort(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM