I have an ArrayList of object. The object contain attributes date
and value
. So I want to sort the objects on the date
, and for all objects in the same date I want to sort them on value
. How can I do that?
sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.
1. Creating Comparators for Multiple Fields. To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.
Implement a custom Comparator
, then use Collections.sort(List, Comparator)
. It will probably look something like this:
public class FooComparator implements Comparator<Foo> {
public int compare(Foo a, Foo b) {
int dateComparison = a.date.compareTo(b.date);
return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
}
}
Collections.sort(foos, new FooComparator());
public static <T> void sort(List<T> list, final List<Comparator<T>> comparatorList) {
if (comparatorList.isEmpty()) {//Always equals, if no Comparator.
throw new IllegalArgumentException("comparatorList is empty.");
}
Comparator<T> comparator = new Comparator<T>() {
public int compare(T o1, T o2) {
for (Comparator<T> c:comparatorList) {
if (c.compare(o1, o2) > 0) {
return 1;
} else if (c.compare(o1, o2) < 0) {
return -1;
}
}
return 0;
}
};
Collections.sort(list, comparator);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With