I have a list of objects I need to sort according to properties of one of their fields. I've heard that SortedMap and Comparators are the best way to do this.
EDIT: This code is giving me an error:
private TreeMap<Ktr> collection = new TreeMap<Ktr>();
(Ktr implements Comparator<Ktr>
). Eclipse says it is expecting something like TreeMap<K, V>
, so the number of parameters I'm supplying is incorrect.
Comparable
with your existing objects, although you could instead create a Comparator
and pass it to the SortedMap
.Comparable
and Comparator
are two different things; a class implementing Comparable
compares this
to another object, while a class implementing Comparator
compares two other objects.Comparable
, you don't need to pass anything special into the constructor. Just call new TreeMap<MyObject>()
. (Edit: Except that of course Maps
need two generic parameters, not one. Silly me!)Comparator
, pass an instance of that class into the constructor.TreeMap
Javadocs.Edit: On re-reading the question, none of this makes sense. If you already have a list, the sensible thing to do is implement Comparable
and then call Collections.sort
on it. No maps are necessary.
A little code:
public class MyObject implements Comparable<MyObject> {
// ... your existing code here ...
@Override
public int compareTo(MyObject other) {
// do smart things here
}
}
// Elsewhere:
List<MyObject> list = ...;
Collections.sort(list);
As with the SortedMap
, you could instead create a Comparator<MyObject>
and pass it to Collections.sort(List, Comparator)
.