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);
...
}
Because the Date class is a subclass that implements the Compatible interface, the Date class also has a For example, you can create the following The Use this comparator to sort the ArrayList according to the questioner' p> If you do not want to reuse a particular comparator elsewhere, simply define it as an unnamed local inner class in the method. The above three are the same logic and you will see the same result.compareTo
method like String
booleanComparator
classes:public class CustomComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}
compare() method must return a value of type
int' rather than a value of type . p>
Collections.sort(Database.arrayList, new CustomComparator());
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));
© 2024 OneMinuteCode. All rights reserved.