It is not possible to sort a HashMap. If you need a sorted map take a look at TreeMap
.
What about adding the rating value to the Movie
class and let it implement Comparable
?
public class Movie implements Comparable<Movie> {
private Float rating;
public Movie(Float rating) {
this.rating = rating;
}
public Float getRating() {
return rating;
}
public int compareTo(Movie param) {
return param.getRating().compareTo(rating);
}
@Override
public String toString() {
return String.valueOf(rating);
}
}
Then you can use your Movie
class like this:
public static void main(String[] args) {
Set<Movie> movies = new HashSet<Movie>();
movies.add(new Movie(0.6f));
movies.add(new Movie(0.5f));
movies.add(new Movie(0.7f));
movies.add(new Movie(0.2f));
// Movie.class has to implement Comparable
System.out.println("First option:");
List<Movie> list = new ArrayList<Movie>(movies);
Collections.sort(list);
printMovies(list);
// Works without implementing Comparable in Movie.class
System.out.println("\nSecond option:");
List<Movie> secondList = new ArrayList<Movie>(movies);
Collections.sort(secondList, new Comparator<Movie>() {
public int compare(Movie movie1, Movie movie2) {
return movie2.getRating().compareTo(movie1.getRating());
}
});
printMovies(secondList);
}
private static void printMovies(List<Movie> list) {
for (Movie movie : list) {
System.out.println(movie);
}
}
Output:
First option:
0.7
0.6
0.5
0.2
Second option:
0.7
0.6
0.5
0.2
If you always want to sort the movies in the same way (from best to worse), I would choose the first option. If you always need different sort algorithms I would choose the second option, but even if your Movie
class implements Comparable
you can always provide a different Comparator
as shown in the example.