public class CustomComparator implements Comparator<CustomObject>
{
@Override
public int compare(CustomObject o1, CustomObject o2) {
return o1.getId().compareTo(o2.getId());
}
}
Then you can use the Collections classes Collections.sort() method:
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}
};
Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);
Additionally, if CustomObjectimplements Comparable, then just use Collections.sort(list)
The question is: "Sort Collection". So you can't use Collections.sort(List<T> l, Comparator<? super T> comparator).
Some tips:
For Collection type:
Comparator<String> defaultComparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
};
Collection<String> collection = getSomeStringCollection();
String[] strings = collection.toArray(new String[collection.size()]);
Arrays.sort(strings, defaultComparator);
List<String> sortedStrings = Arrays.asList(strings);
Collection<String> collection = getSomeStringCollection();
List<String> list = new ArrayList(collection);
Collections.sort(list, defaultComparator);
collection = list; // if you wish
For List type:
List<String> list = getSomeStringList();
Collections.sort(list, defaultComparator);
For Set type:
Set<String> set = getSomeStringSet();
// Than steps like in 'For Collection type' section or use java.util.TreeSet
// TreeSet sample:
// Sorted using java.lang.Comparable.
Set<String> naturalSorted = new TreeSet(set);
Set<String> set = getSomeStringSet();
Set<String> sortedSet = new TreeSet(defaultComparator);
sortedSet.addAll(set);
Java 8 version. There is java.util.List#sort(Comparator<? super E> c) method
List<String> list = getSomeStringList();
list.sort(defaultComparator);
or
List<String> list = getSomeStringList();
list.sort((String o1, String o2) -> o1.compareTo(o2));
or for types that implements Comparable:
List<String> list = getSomeStringList();
list.sort(String::compareTo);
To be super clear, Collection.sort(list, compartor) does not return anything so something like this list = Collection.sort(list, compartor); will throw an error (void cannot be converted to [list type]) and should instead be Collection.sort(list, compartor)