How to use Comparator in Java to sort

I learned how to use the comparable but I’m having difficulty with the Comparator. I am having a error in my code: Exception in thread “main” java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable at java.util.Arrays.mergeSort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at java.util.Collections.sort(Unknown Source) at New.TestPeople.main(TestPeople.java:18) Here is my code: import java.util.Comparator; public class People implements Comparator … Read more

Sort ArrayList of custom Objects by property

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 … Read more

Java : Comparable vs Comparator [duplicate]

When your class implements Comparable, the compareTo method of the class is defining the “natural” ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true. A Comparator is its own definition of how to … Read more

Java TreeMap Comparator

You can not sort TreeMap on values. A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare on keys. To provide sort on … Read more

Sort ArrayList of custom Objects by property

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: … Read more