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: 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: A slightly shorter way to write all this, if you don’t need to reuse your comparator, is 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

How to use Comparator in Java to sort

There are a couple of awkward things with your example class: it’s called People while it has a price and info (more something for objects, not people); when naming a class as a plural of something, it suggests it is an abstraction of more than one thing. Anyway, here’s a demo of how to use a Comparator<T>: EDIT And an … Read more

Using a comparator function to sort

You’re passing the comparator as the key function. You should be passing it as the cmp, wrapped in some kind of function that turns it into a proper comparator. (Although actually, you should be using key functions: Also note that sortedDict will not actually be a dict, so the name is rather confusing.)

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