Home > Back-end >  get 2 keys by 1 value java hashmap
get 2 keys by 1 value java hashmap

Time:10-15

i make top players in real time and I need to get the key (player's nickname) by the value of his points

I get the key using this:

HashMap<Player, Integer> score  = new HashMap<>();

    for(Player key: score.keySet()) {
        if(score.get(key).equals(VALUE OF POINT)) {
            Player = key;
        }
    }

everything works fine, but it can happen that the players have the same number of points and if you search, you will find only one key

how to get the second key?

CodePudding user response:

Create a player list that will gather the players that share the same score points

List<Player> sameScorePlayers = new ArrayList<>();
for(Player key: score.keySet()) {
    if(score.get(key).equals(VALUE OF POINT)) {
        sameScorePlayers.add(key);
    }
} 

This way sameScorePlayers will hold not only two but all players that have the same points.

  • Related