Overview
For sorting there are always two approaches:
- Make the class
Comparable
- Use a
Comparator
I'll assume your values are some sort of class like
public class Entry {
private final String text;
private final int count;
// getters, constructor, toString, ...
}
Comparable
For the first option, simply let your class implement Comparable
with a logic that first uses the count
and then, if it is equal, considers the text
.
public class Entry implements Comparable<? extends Entry> {
private final String text;
private final int count;
// getters, constructor, toString, ...
@Override
public int compareTo(Entry other) {
int countResult = -1 * Integer.compare(count, other.count);
return countResult != 0 ? countResult : text.compareTo(other.text);
}
}
Then simply sort your collection:
Collections.sort(entries);
The -1 *
is to get the sorting-by-count descending instead of the default, ascending.
Comparator
You can do the very same using a Comparator
. Fortunately, we got some nice helper methods since Java 8 that make this even simpler, here is the code:
Comparator<Entry> comparator = Comparator.comparingInt(Foo::getValue)
.reversed()
.thenComparing(Foo::getText);
And then you just give that to the sorter:
entries.sort(comparator);