1

I know there are a number of posts that describe how to sort a hashmap in reverse. I've tried them and I've struggled to make it work. I'm relatively new to Java.

Below, I can print the hashmap in order from lowest double to highest double, but how do I sort it so the highest double comes first? I've followed this post unsuccessfully.

I want to sort the following in reverse order the hashMap called "lines":

public void sortResults(HashMap<Double, TextObject> lines) {
    Map<Double,TextObject> sortedMap = new TreeMap<Double,TextObject>(lines);
    
    
    
    System.out.println("**************************************");
        for (Map.Entry<Double, TextObject> entry : sortedMap.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + " Value : " + entry.getValue());
        }
        System.out.println();
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Katie Melosto
  • 1,047
  • 2
  • 14
  • 35
  • 1
    Use a reverse order comparator to initialize your TreeMap, for example. https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reverseOrder-- – JB Nizet Nov 24 '19 at 19:14
  • Does this answer your question? [TreeMap how does it sort](https://stackoverflow.com/questions/13642636/treemap-how-does-it-sort) – second Nov 24 '19 at 19:15
  • Hi, check this out https://www.baeldung.com/java-treemap#custom-sorting-in-treemap – Sergei Nenashev Nov 24 '19 at 19:15

1 Answers1

2

You can create TreeMap with reverse comparator and then use putAll to add lines

Map<Double,TextObject> sortedMap = new TreeMap<Double,TextObject>(Comparator.reverseOrder());

sortedMap.putAll(lines);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98