java - New to HashMap : how can I sort it? -


so have hashmap looking :

hashmap<movie, float> movies; 

it contains movies global ratings floats, , want sort movies best worst.

i had in collections.sort() have no idea if can it...

it not possible sort hashmap. if need sorted map take @ treemap.

what adding rating value movie class , let 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 can use movie class 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 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) {     (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 want sort movies in same way (from best worse), choose first option. if need different sort algorithms choose second option, if movie class implements comparable can provide different comparator shown in example.


Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -