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
Code (Java): Map<UUID, Integer> mapReversed = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)) This should work
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));
This uses the key to sort things, I want my value to be sorted It's not only reversing, it's also sorting
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