Can you sort ArrayList with a specific method of objects?

Asked 2 years ago, Updated 2 years ago, 149 views

I understand that you can arrange the ArrayLists with a comparator. But if you look at all the examples that use compareTo, it seems to be a method for strings.

I want to sort the ArrayList with a specific method of objects. For example, getStartDay() of the Date object. So to compare the values of the objects, item1.getStartDate().I would like to know if the logic of before(item2.getStartDate()) can be implemented as follows.:

public class CustomComparator {
    public boolean compare(Object object1, Object object2) {
        return object1.getStartDate().before(object2.getStartDate());
    }
}

public class RandomName {
    ...
    Collections.sort(Database.arrayList, new CustomComparator);
    ...
}

date java-8 java comparator sorting

2022-09-22 22:02

1 Answers

Because the Date class is a subclass that implements the Compatible interface, the Date class also has a compareTo method like String

For example, you can create the following Comparator classes:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return a value of type int' rather than a value of type boolean.

Use this comparator to sort the ArrayList according to the questioner'

Collections.sort(Database.arrayList, new CustomComparator());

If you do not want to reuse a particular comparator elsewhere, simply define it as an unnamed local inner class in the method.

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});
Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
Database.arrayList.sort(Comparators.comparing(MyObject::getStartDate));

The above three are the same logic and you will see the same result.


2022-09-22 22:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.