0

I have a HashMap<String, Integer> list and I want to sort it by integers and be able to get a key in a certain order (for example: get the 3rd, or 5th key). How do I go by doing this?

Adya
  • 41
  • 3
  • What do you mean by "I have a HashMap list"? Do you mean `List>` or something else? Also what do you want to get as result when you "get the 3rd"? – Pshemo Aug 21 '21 at 14:30
  • Basically, I'm working on a scoreboard, and I want the player to see their placement, so basically where they are positioned, using the values. – Adya Aug 21 '21 at 14:32
  • How about instead of using map using `List` where ScoreInfo will be class holding `String name; Integer score`? – Pshemo Aug 21 '21 at 14:38

1 Answers1

3

You can't sort a HashMap. The order of entries within a HashMap is kinda random.

You could use myMap.keySet() to extract the keys (in random order) and put them in a new ordered collection (= List or SortedSet), for example: new ArrayList<>(myMap.keySet());. And then sort this List.

Or you use a SortedMap with a custom Comparator instead of a HashMap.

Benjamin M
  • 23,599
  • 32
  • 121
  • 201