Solved Sort hashmap<UUID, Long>

Discussion in 'Spigot Plugin Development' started by Jumbo_1907, Jun 10, 2018.

Thread Status:
Not open for further replies.
  1. Hey everyone,
    What is the best solution to sort a hashmap like this:

    Input:
    UUID1, 5
    UUID2, 500
    UUID3, 250
    UUID4, 1000

    Output:
    UUID4, 1000
    UUID2, 500
    UUID3, 250
    UUID1, 5
     
  2. Code (Java):
    Map<UUID, Integer> mapReversed = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))
    This should work
     
  3. I found this somewhere on stackoverflow and you may be able to use it for this:

    Code (Java):
    Map<Integer, String> sortedMap =
         unsortedMap.entrySet().stream()
        .sorted(Entry.comparingByValue())
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                                  (e1, e2) -> e1, LinkedHashMap::new));
     
  4. This uses the key to sort things, I want my value to be sorted

    It's not only reversing, it's also sorting
     
    #4 Jumbo_1907, Jun 10, 2018
    Last edited: Jun 10, 2018
  5. If you want both keys and values sorted, get the keySet() and values(), sort them with Collection#sort, get an iterator of each. Create a new HashMap and loop through either keys or values (assuming they are the same length - they should be if it's a HashMap which I don't think allows null keys), and add Iterator#next as keys and valhes

    Sent from my SM-G903F using Tapatalk
     
Thread Status:
Not open for further replies.