This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/2…

Issue an overview

I know that ArrayList sorts with a Comparator, but all the compareTo examples that people use are based on the String class.

I want to sort using an attribute from a custom object, such as a Date object (getStartDay()). Item1.getstartdate ().before(item2.getStartDate())).

So I want to know can I write it like this?

public class CustomComparator {
    public boolean compare(Object object1, Object object2) {
        returnobject1.getStartDate().before(object2.getStartDate()); }}public class RandomName {... Collections.sort(Database.arrayList,newCustomComparator); . }Copy the code

Best answer

Since Data implements the Comparable interface, it will have a compareTo method like the String class. So your Comparator can be written like this.

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

Compare () must return an int, not a Boolean. So you can’t return Boolean as you originally planned.

The sort code is exactly what you wrote

Collections.sort(Database.arrayList, new CustomComparator());
Copy the code

If your Comparator doesn’t need reuse, you can write it more easily using anonymous inner class methods, as shown below

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        returno1.getStartDate().compareTo(o2.getStartDate()); }});Copy the code

For the last approach, use a new Java1.8 feature: lambda expressions

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
Copy the code

or

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
Copy the code

There is also a built-in method to automatically generate comparators for properties that implement Comparable

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));
Copy the code

These are equivalent forms