#sort a HashMap by value size
1 messages · Page 1 of 1 (latest)
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
a hashmap has no order
its totally random and cant be sorted
u can either use a SortedMap, such as TreeMap
or sort afterwards, after u retrieved ur values
for example in a list
They sort by the CompareTo definition by default, but you can add your own Comparator when constructing the map if you want a custom sort
In this case you will want that as you want big to small. Default is small to large
Actually maps are sorted by keys, not values
If they are sorted
Idk if theres a value sorted map?
You can provide a Comparator to a TreeMap in which case it will be used for sorting, instead of keys
If you use a TreeMap, you won't need to
How so? Wont the keys be sorted and not the values?
Op wants sorted integers not sorted strings
So by your logic the sorted keys will now point at different values? 
Wont the comparator be a Predicate<String> object with no access to the Integer value? And thus no ability to sort on that?
Actually, yes
List<Integer> list = new ArrayList<>(map.values());
list.sort(Comparator.reverseOrder());
That would do it
Wont stay updated if the map changes tho!
maps cant do that
u have to sort afterwards, outside of the map
its impossible by design to keep a map sorted by its values
(while having direct access to them via key)
perhaps u never intended to have a map and instead want a list of pairs? perhaps u intended to have the map the other way around?
if none of these, u have to do the sorting afterwards
@dawn ivy
my solution:
public static void main(String... args) {
Map<String, Integer> map = new HashMap<>();
map.put("james", 1);
map.put("malarkey", 5);
map.put("fred", 2);
System.out.println(map); // will be unordered
Map<String, Integer> sortedMap = new TreeMap<>(
(String a, String b) -> map.get(b).compareTo(map.get(a)) // reversed sort using values from map
);
sortedMap.putAll(map); // TreeMap sorts new elements based on the Comparator used in the above line
System.out.println(sortedMap); // will be ordered by value (large to small)
}
note that the new map will again not reflect any changed made in the old one
Detected code, here are some useful tools:
public static void main(String...args) {
Map<String, Integer> map = new HashMap<>();
map.put("james", 1);
map.put("malarkey", 5);
map.put("fred", 2);
System.out.println(map);
// will be unordered
Map<String, Integer> sortedMap = new TreeMap<>((String a, String b) -> map.get(b).compareTo(map.get(a)) // reversed sort using values from map
);
sortedMap.putAll(map);
// TreeMap sorts new elements based on the Comparator used in the above line
System.out.println(sortedMap);
// will be ordered by value (large to small)
}
also the new map will cause issues if you then start altering it, because it will keep looking at the original map
so definitely keep it local and dont return it or save it somewhere 😛
you sort it right when you need to access the values in an ordered manner
and then you dont use sortedMap again, as it will behave weirdly if you alter it
original map will be fine tho
the object you get will be the same
but Java will treat it as a Map instead of a HashMap, meaning you cannot use HashMap-specific methods (idk if those exist)
its basically saying, "i just want any map, i dont really care what kind it is"
to be clear in this case it does not affect behavior at all
arguably sortedMap should have been defined as a SortedMap because i explicitly require one in this context. but again, thats more a coding convention / readability thing, not something that would affect behavior
based on ur explanation, i would definitely not sort the map itself, but the highscore list. as the name implies, its a list at that point
List<String> highscoreNames = map.entrySet()
.stream()
.sorted(entry -> entry.getValue())
.map(entry -> entry.getKey())
.toList();
sth sth along those lines
or use some extra class if u need more data, such as the score
record UserHighscore(String username, int score) {}
u do
List<UserHighscore> highscoreBoard = map.entrySet()
.stream()
.map(entry -> new UserHighScore(entry.getKey(), entry.getValue())
.sorted(Comparator.comparingInt(UserHighScore::score).reversed())
.toList();
just so u get an idea what approach im talking about
u dont have to use streams if ur not familiar with that
but the approach will be the same
i.e. map -> list of user highscore -> sort list