1279

I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.

I wanted to sort an ArrayList of custom objects by one of their properties: a Date object (getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:

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);
    ...
}
james.garriss
  • 12,959
  • 7
  • 83
  • 96
Samuel
  • 18,286
  • 18
  • 52
  • 88
  • 4
    Related: http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts – BalusC May 06 '10 at 21:34
  • 2
    [Answer by @Yishai in this post](http://stackoverflow.com/questions/1421322/how-do-i-sort-a-list-with-multiple-sort-parameters#1421537) demonstrates elegant use of enum for custom sorting and grouped sorting (multiple arguments) utilizing comparator chaining. – gunalmel Sep 16 '12 at 04:03

29 Answers29

1713

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

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 an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

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

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

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

Since

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

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

And List has a sort(Comparator) method, so you can shorten this even further:

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

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

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

All of these are equivalent forms.

Community
  • 1
  • 1
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • 41
    +1 for mentioning that it should return `int` and that you'd better to use `Date#compareTo()` for this. Why this isn't upvoted above the other answer is beyond me. This link may also be useful: [Object Ordering Tutorial at Sun.com](http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html). – BalusC May 06 '10 at 21:26
  • 7
    I think the answer best should also include the proper way to do it in Java 8. Collections.sort(list, Comparator.comparing(MyObject::getStartDate)); which reads better and is less error prone. It's very easy to write return o1.getStartDate().compareTo(o1.getStartDate()); – Kuba May 16 '14 at 14:00
  • 2
    Comparator class should be static :) – Jarmez De La Rocha Jun 27 '14 at 09:14
  • 1
    @JarmezDeLaRocha: I didn't specify whether the comparator was declared inside another class; if it is, then yes, you would want to make it static. – Michael Myers Jun 28 '14 at 22:42
  • you can use to compare int values like this "return o1.getDistance()-o2.getDistance();" – Zafer Nov 19 '15 at 18:18
  • what happens when `o1.getStartDate()` returns null? – Taylor O'Connor Dec 31 '15 at 19:13
  • @Taylor O'Connor: it throws a NullPointerException. – Michael Myers Dec 31 '15 at 19:48
  • 4
    @Kuba better yet, use `List.sort()`. – shmosel Apr 25 '16 at 18:31
  • 2
    The order of String sort is asc by default when use `s1.compareTo(s2)` and desc when use `s2.compareTo(s1)` – Wendel Jun 03 '16 at 11:52
  • 2
    If you are using Java 8, see if you can get rid of `Date` in favour of one of the new and more programmer frindly classes in the `java.time` package. – Ole V.V. Mar 25 '17 at 16:25
  • 3
    This solution does not work on Android API <24. Do you guys know a solution for this? – Jim Clermonts Mar 15 '18 at 16:37
  • In case anyone is looking at this because they're on Android API <24, you can use `Collections.sort()` to sort your lists. – Rajiv May 08 '19 at 04:20
  • 1
    Nowadays you can use: `Collections.sort(Database.arrayList, Comparator.comparing(Object::method));` – JFreeman Aug 12 '20 at 03:21
  • 1
    @JFreeman: Thanks for commenting! I didn't include that version because it's nearly identical to the last version I posted, only a little longer to type. – Michael Myers Aug 12 '20 at 14:09
  • There's a missing, yet extremely important detail: in what order does .compareTo() work? Ascending? Descending? – StackLloyd Feb 08 '22 at 09:28
201

Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).

Two examples:

public class Number implements Comparable<Number> {
    private int value;

    public Number(int value) { this.value = value; }
    public int compareTo(Number anotherInstance) {
        return this.value - anotherInstance.value;
    }
}

public class Chair {
    private int weight;
    private int height;

    public Chair(int weight, int height) {
        this.weight = weight;
        this.height = height;
    }
    /* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getWeight() - chair2.getWeight();
    }
}
class ChairHeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getHeight() - chair2.getHeight();
    }
}

Usage:

List<Number> numbers = new ArrayList<Number>();
...
Collections.sort(numbers);

List<Chair> chairs = new ArrayList<Chair>();
// Sort by weight:
Collections.sort(chairs, new ChairWeightComparator());
// Sort by height:
Collections.sort(chairs, new ChairHeightComparator());

// You can also create anonymous comparators;
// Sort by color:
Collections.sort(chairs, new Comparator<Chair>() {
    public int compare(Chair chair1, Chair chair2) {
        ...
    }
});
Björn
  • 29,019
  • 9
  • 65
  • 81
  • I tried that - but when I want to access the comparator class ChairWeightComparator outside in any other class I do not get access to this class (of course not since its not public). Do I need to create a new public ChairWeightComparator class in a separate file? - am I really the first one to try this after 3 years or did I miss sth? – user387184 Mar 23 '14 at 09:01
  • @user387184 - simply make it public, and put it in it's own file (preferably it's own package as well) and you'll be able to use it everywhere in you project. No need to create an additional class! – Björn Mar 23 '14 at 17:36
  • you mean create a new file - not a class and put in the code: "class ChairWeightComparator implements Comparator {...." ? – user387184 Mar 23 '14 at 18:28
  • @user387184, exactly - but with the key word `public` in front of `class`. – Björn Mar 24 '14 at 06:00
  • This is not working on my Laptop. It shows int cannot be dereferenced error. How to correct it ? – Alex Oct 17 '20 at 04:03
164

For sorting an ArrayList you could use the following code snippet:

Collections.sort(studList, new Comparator<Student>(){
    public int compare(Student s1, Student s2) {
        return s1.getFirstName().compareToIgnoreCase(s2.getFirstName());
    }
});
blackpanther
  • 10,998
  • 11
  • 48
  • 78
  • 1
    Anybody using lambda http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property/25686715#25686715 – Sorter Sep 05 '14 at 13:13
  • That sorts but gives double value for each element – Samir Sep 23 '16 at 17:41
  • This is not working on my Laptop. It shows int cannot be dereferenced error. How to correct it ? – Alex Oct 17 '20 at 04:03
47

JAVA 8 lambda expression

Collections.sort(studList, (Student s1, Student s2) ->{
        return s1.getFirstName().compareToIgnoreCase(s2.getFirstName());
});

OR

Comparator<Student> c = (s1, s2) -> s1.firstName.compareTo(s2.firstName);
studList.sort(c)
Sorter
  • 9,704
  • 6
  • 64
  • 74
45

Yes, you can. There are two options with comparing items, the Comparable interface, and the Comparator interface.

Both of these interfaces allow for different behavior. Comparable allows you to make the object act like you just described Strings (in fact, String implements Comparable). The second, Comparator, allows you to do what you are asking to do. You would do it like this:

Collections.sort(myArrayList, new MyComparator());

That will cause the Collections.sort method to use your comparator for it's sorting mechanism. If the objects in the ArrayList implement comparable, you can instead do something like this:

Collections.sort(myArrayList);

The Collections class contains a number of these useful, common tools.

aperkins
  • 12,914
  • 4
  • 29
  • 34
  • This is not working on my Laptop. It shows int cannot be dereferenced error. How to correct it ? – Alex Oct 17 '20 at 04:03
38

With Java 8 you can use a method reference for your comparator:

import static java.util.Comparator.comparing;

Collections.sort(list, comparing(MyObject::getStartDate));
assylias
  • 321,522
  • 82
  • 660
  • 783
  • @user387184 unfortunately android does not support Java 8, although there may be a [workaround](http://zserge.com/blog/android-lambda.html) (I haven't tested it). – assylias Mar 23 '14 at 09:20
15

Since technologies appear everyday, the answer will change in the time. I took a look at LambdaJ and seems very interesting.

You can try solving these tasks with LambdaJ. You can find it here: http://code.google.com/p/lambdaj/

Here you have an example:

Sort Iterative

List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
        public int compare(Person p1, Person p2) {
           return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
        }
});

Sort with lambda

List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge()); 

Of course, having this kind of beauty impacts in the performance (an average of 2 times), but can you find a more readable code?

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • That sorts but gives double value for each element how to avoid it – Samir Sep 23 '16 at 17:41
  • @Sam, it shouldn't... it's working as expected. Unless you are using a new version with a bug, which I recommend you to post it in the forum. Anyway, this answer was post prior to java 8, if you use it, then it will much better than using lambdaj – Federico Piazza Sep 23 '16 at 19:30
  • I had to remove even items in a foreach loop other wise it gives me double of each content. – Samir Sep 24 '16 at 11:06
13

Function & method reference

The Collections.sort method can sort a List using a Comparator you pass. That Comparator can be implemented using the Comparator.comparing method where you can pass a method reference as the necessary Function. Fortunately, the actual code is much simpler and shorter than this description.

For Java 8:

Collections.sort(list, comparing(ClassName::getName));

or

Collections.sort(list, comparing(ClassName::getName).reversed());

Another way is

Collections.sort(list, comparing(ClassName::getName, Comparator.nullsLast(Comparator.naturalOrder())));
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Arun
  • 2,312
  • 5
  • 24
  • 33
13
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

public class test {

public static class Person {
    public String name;
    public int id;
    public Date hireDate;

    public Person(String iname, int iid, Date ihireDate) {
        name = iname;
        id = iid;
        hireDate = ihireDate;
    }

    public String toString() {
        return name + " " + id + " " + hireDate.toString();
    }

    // Comparator
    public static class CompId implements Comparator<Person> {
        @Override
        public int compare(Person arg0, Person arg1) {
            return arg0.id - arg1.id;
        }
    }

    public static class CompDate implements Comparator<Person> {
        private int mod = 1;
        public CompDate(boolean desc) {
            if (desc) mod =-1;
        }
        @Override
        public int compare(Person arg0, Person arg1) {
            return mod*arg0.hireDate.compareTo(arg1.hireDate);
        }
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    SimpleDateFormat df = new SimpleDateFormat("mm-dd-yyyy");
    ArrayList<Person> people;
    people = new ArrayList<Person>();
    try {
        people.add(new Person("Joe", 92422, df.parse("12-12-2010")));
        people.add(new Person("Joef", 24122, df.parse("1-12-2010")));
        people.add(new Person("Joee", 24922, df.parse("12-2-2010")));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Collections.sort(people, new Person.CompId());
    System.out.println("BY ID");
    for (Person p : people) {
        System.out.println(p.toString());
    }

    Collections.sort(people, new Person.CompDate(false));
    System.out.println("BY Date asc");
    for (Person p : people) {
        System.out.println(p.toString());
    }
    Collections.sort(people, new Person.CompDate(true));
    System.out.println("BY Date desc");
    for (Person p : people) {
        System.out.println(p.toString());
    }

}

}
CharlesW
  • 625
  • 6
  • 14
10

Best easy way with JAVA 8 is for English Alphabetic sort

Class Implementation

public class NewspaperClass implements Comparable<NewspaperClass>{
   public String name;

   @Override
   public int compareTo(NewspaperClass another) {
      return name.compareTo(another.name);
   }
}

Sort

  Collections.sort(Your List);

If you want to sort for alphabet that contains non English characters you can use Locale... Below code use Turkish character sort...

Class Implementation

public class NewspaperClass implements Comparator<NewspaperClass> {
   public String name;
   public Boolean isUserNewspaper=false;
   private Collator trCollator = Collator.getInstance(new Locale("tr_TR"));



   @Override
   public int compare(NewspaperClass lhs, NewspaperClass rhs) {
      trCollator.setStrength(Collator.PRIMARY);
      return trCollator.compare(lhs.name,rhs.name);
   }
}

Sort

Collections.sort(your array list,new NewspaperClass());
Ucdemir
  • 2,852
  • 2
  • 26
  • 44
7

You can Sort using java 8

yourList.sort(Comparator.comparing(Classname::getName));

or

yourList.stream().forEach(a -> a.getBObjects().sort(Comparator.comparing(Classname::getValue)));
Prateek Kapoor
  • 947
  • 9
  • 18
6

Java 8 Lambda shortens the sort.

Collections.sort(stdList, (o1, o2) -> o1.getName().compareTo(o2.getName()));
Pshemo
  • 122,468
  • 25
  • 185
  • 269
javasenior
  • 1,786
  • 2
  • 22
  • 26
6

From Java 8 and onward we don't have to use Collections.sort() directly. List interface has a default sort() method:

List<User> users = Arrays.asList(user1,user2,user3);
users.sort( (u1, u2) -> { 
return u1.getFirstName.compareTo(u2.getFirstName());}); 

See http://visvv.blogspot.in/2016/01/sorting-objects-in-java-8.html.

Neil Masson
  • 2,609
  • 1
  • 15
  • 23
5

I found most if not all of these answers rely on the underlying class (Object) to implement comparable or to have a helper comparable interface.

Not with my solution! The following code lets you compare object's field by knowing their string name. You could easily modify it not to use the name, but then you need to expose it or construct one of the Objects you want to compare against.

Collections.sort(anArrayListOfSomeObjectPerhapsUsersOrSomething, new ReflectiveComparator(). new ListComparator("name"));

public class ReflectiveComparator {
    public class FieldComparator implements Comparator<Object> {
        private String fieldName;

        public FieldComparator(String fieldName){
            this.fieldName = fieldName;
        }

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public int compare(Object object1, Object object2) {
            try {
                Field field = object1.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);

                Comparable object1FieldValue = (Comparable) field.get(object1);
                Comparable object2FieldValue = (Comparable) field.get(object2);

                return object1FieldValue.compareTo(object2FieldValue);
            }catch (Exception e){}

            return 0;
        }
    }

    public class ListComparator implements Comparator<Object> {
        private String fieldName;

        public ListComparator(String fieldName) {
            this.fieldName = fieldName;
        }

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public int compare(Object object1, Object object2) {
            try {
                Field field = object1.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Comparable o1FieldValue = (Comparable) field.get(object1);
                Comparable o2FieldValue = (Comparable) field.get(object2);

                if (o1FieldValue == null){ return -1;}
                if (o2FieldValue == null){ return 1;}
                return o1FieldValue.compareTo(o2FieldValue);
            } catch (NoSuchFieldException e) {
                throw new IllegalStateException("Field doesn't exist", e);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException("Field inaccessible", e);
            }
        }
    }
}
Kevin Parker
  • 16,975
  • 20
  • 76
  • 105
5

You can try Guava Ordering:

Function<Item, Date> getStartDate = new Function<Item, Date>() {
    public Date apply(Item item) {
        return item.getStartDate();
    }
};

List<Item> orderedItems = Ordering.natural().onResultOf(getStartDate).
                          sortedCopy(items);
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
5

You can use the Bean Comparator to sort on any property in your custom class.

camickr
  • 321,443
  • 19
  • 166
  • 288
5

Yes, that's possible for instance in this answer I sort by the property v of the class IndexValue

    // Sorting by property v using a custom comparator.
    Arrays.sort( array, new Comparator<IndexValue>(){
        public int compare( IndexValue a, IndexValue b ){
            return a.v - b.v;
        }
    });

If you notice here I'm creating a anonymous inner class ( which is the Java for closures ) and passing it directly to the sort method of the class Arrays

Your object may also implement Comparable ( that's what String and most of the core libraries in Java does ) but that would define the "natural sort order" of the class it self, and doesn't let you plug new ones.

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
5

Well if you using Java 8 or older version Here is the Best solution.

Collections.sort(studentList, Comparator.comparing(Student::getCgpa).reversed().thenComparing(Student:: getFname).thenComparing(Student::getId));

In this case, it will first sort with 'getCgpa' first and for the second part it will sort with getFname and getId. Which is field into the pojo class.

Kishan Bheemajiyani
  • 3,429
  • 5
  • 34
  • 68
3

This code snippets might be useful. If you want to sort an Object in my case I want to sort by VolumeName:

public List<Volume> getSortedVolumes() throws SystemException {
    List<Volume> volumes = VolumeLocalServiceUtil.getAllVolumes();
    Collections.sort(volumes, new Comparator<Volume>() {
        public int compare(Volume o1, Volume o2) {
            Volume p1 = (Volume) o1;
            Volume p2 = (Volume) o2;
            return p1.getVolumeName().compareToIgnoreCase(
                    p2.getVolumeName());
        }
    });
    return volumes;
}

This works. I use it in my jsp.

Laura Liparulo
  • 2,849
  • 26
  • 27
3

your customComparator class must implement java.util.Comparator in order to be used. it must also overide compare() AND equals()

compare() must answer the question: Is object 1 less than, equal to or greater than object 2?

full docs: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html

Vinny
  • 789
  • 8
  • 16
3

With this library here you can sort the list of custom objects on multiple columns. The library uses version 8.0 features. Sample is also available there. Here is a sample to do

SortKeys sortKeys = new SortKeys();
sortKeys.addField("firstName")
            .addField("age", true); // This (true) will sort the age descending

// Other ways to specify a property to the sorter are
//      .addField("lastName", String.class);
//      .addField("dob", Date.class, true);

// Instantiate a ListSorter
ListSorter listSorter = new ListSorter();

// Pass the data to sort (listToSort) and the "by keys" to sort (sortKeys)
List sortedList = (List<Person>) listSorter.sortList(listToSort, sortKeys);
Shriram M.
  • 383
  • 1
  • 7
3

You can have a look into this presentation hold at the Java Forum in Stuttgart Germany in 2016.

Only a few slides use German language, 99% of the content is "English based" Java source code; like

someCollection.sort(
  OurCustomComparator
    .comparing(Person::getName)
    .thenComparing(Person::getId)
);

where OurCustomComparator is using default methods (and other interesting ideas). As shown, leading to very concise code to pick some getter method for sorting; and super simple chaining (or reversing) of sort criteria.

If you are into java8, you find a lot of material there to get you started.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • fyi, presentation link is dead. – AJW Jan 01 '22 at 17:25
  • @AJW Thanks, yeah, there is a reason why I added the code here ... I assumed that the link would break one day. Just no clue where else I could provide that file from . – GhostCat Jan 02 '22 at 18:42
3

New since 1.8 is a List.sort() method instead of using the Collection.sort() so you directly call mylistcontainer.sort()

Here is a code snippet which demonstrates the List.sort() feature:

List<Fruit> fruits = new ArrayList<Fruit>();
fruits.add(new Fruit("Kiwi","green",40));
fruits.add(new Fruit("Banana","yellow",100));
fruits.add(new Fruit("Apple","mixed green,red",120));
fruits.add(new Fruit("Cherry","red",10));

// a) using an existing compareto() method
fruits.sort((Fruit f1,Fruit f2) -> f1.getFruitName().compareTo(f2.getFruitName()));
System.out.println("Using String.compareTo(): " + fruits);
//Using String.compareTo(): [Apple is: mixed green,red, Banana is: yellow, Cherry is: red, Kiwi is: green]

// b) Using a comparable class
fruits.sort((Fruit f1,Fruit f2) -> f1.compareTo(f2));  
System.out.println("Using a Comparable Fruit class (sort by color): " + fruits);
// Using a Comparable Fruit class (sort by color): [Kiwi is green, Apple is: mixed green,red, Cherry is: red, Banana is: yellow]

The Fruit class is:

public class Fruit implements Comparable<Fruit>
{
    private String name;
    private String color;
    private int quantity;

    public Fruit(String name,String color,int quantity)
    { this.name = name; this.color = color; this.quantity = quantity; }

    public String getFruitName() { return name; }        
    public String getColor() { return color; }  
    public int getQuantity() { return quantity; }

    @Override public final int compareTo(Fruit f) // sorting the color
    {
        return this.color.compareTo(f.color);
    }     
    @Override public String toString()
    {   
        return (name + " is: " + color);
    }
} // end of Fruit class   
TylerH
  • 20,799
  • 66
  • 75
  • 101
Norbert
  • 234
  • 1
  • 9
2

using the java-8 stream api you can sort an ArrayList by:

 Comparator<Person> birthdayComparator = Comparator.comparing(Person::getBirthday);
 List<Person> sortedList = list.stream().sorted(birthdayComparator).collect(toList());
pero_hero
  • 2,881
  • 3
  • 10
  • 24
1

I prefer this process:

public class SortUtil
{    
    public static <T> List<T> sort(List<T> list, String sortByProperty)
    {
            Collections.sort(list, new BeanComparator(sortByProperty));
            return list;
    }
}

List<T> sortedList = SortUtil<T>.sort(unsortedList, "startDate");

If you list of objects has a property called startDate, you call use this over and over. You can even chain them startDate.time.

This requires your object to be Comparable which means you need a compareTo, equals, and hashCode implementation.

Yes, it could be faster... But now you don't have to make a new Comparator for each type of sort. If you can save on dev time and give up on runtime, you might go with this one.

DDus
  • 435
  • 6
  • 17
  • 3
    1, this answer was given 2 hours earlier with working code provided as well. There is no need to repost the same solution and clutter the forum especially since BeanComparator is not a standard class, so its not really a solution if the poster doesn't know what you are talking about. If you like the original suggestion you can upvote it and add a comment if you wish. – camickr May 07 '10 at 03:02
0

Using Java 8 use can define the Comparator in one line using Comparator.comparing()

Use any of the following way:

Option 1:

listToBeSorted.sort(Comparator.comparing(CustomObject::getStartDate));

Option 2:

Collections.sort(listToBeSorted, Comparator.comparing(CustomObject::getStartDate));
Sahil Chhabra
  • 10,621
  • 4
  • 63
  • 62
  • 1
    Seems to be a duplicate of [this Answer](https://stackoverflow.com/a/34279142/642706) from 3 years prior. – Basil Bourque Dec 28 '18 at 21:13
  • 1
    Not exactly, only option 2 here is similar to option 1 in the mentioned answer. I feel two different answers can have atleast some similarities if they are answer to the same question. – Sahil Chhabra Dec 29 '18 at 03:20
0

Your custom class can implement the "Comparable" interface, which requires an implementation of the CompareTo method. In the CompareTo method, you can then define what it means that an object is less than or more than the other object. So in your example, it can look something like this:

public class MyCustomClass implements Comparable<MyCustomClass>{

..........

 @Override
public int compareTo(MyCustomClass a) {
    if(this.getStartDate().before(a.getStartDate())){
        return -1;
    }else if(a.getStartDate().before(this.getStartDate())){
        return 1;
    }else {
        return 0;
    }
}

A negative number indicates that this is smaller than the object being compared to. A positive number indicates that this is larger than the compared to object and a Zero means that the objects are equal.

You can then use the collections.sort(myList) to sort your list without having to feed in a comparator. This method also has the advantage of having things sorted automatically if you use a sorted collection data structures like a TreeSet or a TreeMap.

You can check this article if you would like to read more about the Comparable interface (disclosure: I am the author ;) ) https://nullbeans.com/the-java-comparable-interface-automatic-sort-of-collections/

Nullbeans
  • 309
  • 1
  • 8
0

You could also use Springs PropertyComparator if you have just a String property path to the (nested) property you want to sort:

List<SomeObject> list = ...;
PropertyComparator<HitWithInfo> propertyComparator = new PropertyComparator<>(
    "property.nested.myProperty", false, true);
list.sort(propertyComparator);

The drawback is, that this comparator silently ignores properties which does not exist or are not accessible and handles this as null value for comparison. This means, you should carefully test such a comparator or validate the existence of the property path somehow.

xtermi2
  • 470
  • 5
  • 10
-1

I have tried lots of different solutions available on internet but solution which works for me is available at below link.

https://www.java67.com/2017/07/how-to-sort-arraylist-of-objects-using.html