Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Collections.sort keep order on equal elements?

I have a list of objects ordered by a date parameter and want to reorder them by category parameter, but keeping the date order within the category.

Is something like this enough, or do I have to implement a comparator that takes on account the date for objects of the same category?

// sort the list by category asc(, date asc )
Collections.sort((List<Object>)entries, new Comparator<Object>() {

    @Override public int compare(Object elementA, Object elementB) {
        return elementA.category.compareTo(elementB.category); // what happens when elementA.category.equals(elementB.category)?
    }

});
like image 679
NotGaeL Avatar asked Feb 19 '15 18:02

NotGaeL


People also ask

What sorting method does Collections sort use?

Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.

What does collection sort () do?

By default, Collection. sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods: reverseOrder() : Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.

Does collections sort use comparator?

While using the Comparable interface, we do not need to make any changes to the code. This is because the sort functions of the collections class automatically use the compareTo method in the class. However, while we implement the Comparator interface, we need to use the comparator name along with the sort function.

Which collection saves the element in sorted order?

Use TreeSet which gives elements in sorted order.


1 Answers

The code in your question will do what you need it to, since Collections.sort() does preserve the order of equal elements.

From the documentation:

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

In other words, if the entries are ordered by date before the sort(), they will stay ordered by date within each category after the sort().

If you don't want to rely on the original ordering, you can easily extend your comparator to first compare the categories and then break ties using the dates.

like image 164
NPE Avatar answered Sep 19 '22 15:09

NPE