Here's an example of using Comparator
to sort based on an external criteria:
import java.util.*;
class VoteComparator implements Comparator<String> {
final Map<String, Integer> tally;
VoteComparator(Map<String, Integer> tally) {
this.tally = tally;
}
@Override public int compare(String pub1, String pub2) {
int v1 = tally.get(pub1);
int v2 = tally.get(pub2);
return
(v1 < v2) ? -1 :
(v1 > v2) ? +1 :
0;
}
};
This uses just String
for publication for simplicity; you'd want to sort Publication
in your application. This also uses a simple int
to get the vote count, but essentially there has to be a tally service that gives you, given a Publication
, what its Vote
count is.
Note: English is not my first language, so perhaps "tally" isn't the right word for it, but basically some sort of vote registrar, vote recorder, essentially a map between an object, and how many votes it gets.
Then you can sort, using, say, TreeSet
.
public class SortExample {
public static void main(String[] args) {
Map<String, Integer> tally = new HashMap<String, Integer>();
tally.put("foo", 42);
tally.put("bar", 13);
tally.put("Fizz", 3);
tally.put("Buzz", 5);
tally.put("FizzBuzz", 15);
Comparator<String> voteComparator = new VoteComparator(tally);
SortedSet<String> sortedByVote = new TreeSet<String>(voteComparator);
sortedByVote.addAll(tally.keySet());
for (String pub: sortedByVote) {
System.out.println(pub + " (" + tally.get(pub) + " votes)");
}
}
}
This prints:
Fizz (3 votes)
Buzz (5 votes)
bar (13 votes)
FizzBuzz (15 votes)
foo (42 votes)