Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is not possible to sort a HashMap. If you need a sorted map take a look at <a href="http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html" rel="nofollow"><code>TreeMap</code></a>.</p> <p>What about adding the rating value to the <code>Movie</code> class and let it implement <code>Comparable</code>?</p> <pre><code>public class Movie implements Comparable&lt;Movie&gt; { 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); } } </code></pre> <p>Then you can use your <code>Movie</code> class like this:</p> <pre><code>public static void main(String[] args) { Set&lt;Movie&gt; movies = new HashSet&lt;Movie&gt;(); 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&lt;Movie&gt; list = new ArrayList&lt;Movie&gt;(movies); Collections.sort(list); printMovies(list); // Works without implementing Comparable in Movie.class System.out.println("\nSecond option:"); List&lt;Movie&gt; secondList = new ArrayList&lt;Movie&gt;(movies); Collections.sort(secondList, new Comparator&lt;Movie&gt;() { public int compare(Movie movie1, Movie movie2) { return movie2.getRating().compareTo(movie1.getRating()); } }); printMovies(secondList); } private static void printMovies(List&lt;Movie&gt; list) { for (Movie movie : list) { System.out.println(movie); } } </code></pre> <p>Output:</p> <pre><code>First option: 0.7 0.6 0.5 0.2 Second option: 0.7 0.6 0.5 0.2 </code></pre> <p>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 <code>Movie</code> class implements <code>Comparable</code> you can always provide a different <code>Comparator</code> as shown in the example.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload