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 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
booleancompare() method must return a value of type
int' rather than a value of type .
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
Popular Tags
python x 4647
android x 1593
java x 1494
javascript x 1427
c x 927
c++ x 878
ruby-on-rails x 696
php x 692
python3 x 685
html x 656
Popular Questions
© 2025 OneMinuteCode. All rights reserved.