yasgur99 yasgur99 - 1 year ago 76
Java Question

Return Comparator's compare method using a double?

So I have a class to compare the rating of a film. It implements the comparator class as seen below:

public class FilmComparator implements Comparator<Film> {

private Map<Film, List<Rating>> ratings;

public FilmComparator(Map<Film, List<Rating>> ratings) {
this.ratings = ratings;

public int compare(Film o1, Film o2) {
double average1 = average(o1);
double average2 = average(o2);
return average2 - average1; // I cant do this because it need to return an int

private double average(Film f) {
int sum = 0;
for (Rating r : ratings.get(f)) {
sum += r.getValue();
return sum / ratings.get(f).size();

As you can see, the average might not always be an integer. I am wondering how I would be able to have a more accurate compare. For example, I am having issues when the average returns 3.6 for one object but 3.0 for the other. To the compare method, the are the same but I need to show a difference. Is this possible?

Answer Source

Simple, let Double do the work for you. Do

return Double.compare(average1, average2); // or swap if desired
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download