How to check the number of keys that have a specific value in a hash map

I am trying to figure out how to check if hashmap (which in my case can have any number of keys) has only one of the specific value assigned to it. I'm struggling to explain it here.

If I have a hashmap with 10 keys (each of the players in the game assigned to play in the gamma, depending on which "game to play" they are in), and there is only one player with the game state IN_GAME. Then how can I verify that there is really only one key assigned with an IN_GAME value, and there are no two keys with this value?

Hope this makes sense.

+4
source share
3

:

Map<String, String> data = new HashMap<>();
// adding data
long count = data.values().stream().filter(v -> v.equals("IN_GAME")).count();

Count "IN_GAME" .

+3

Iterator .

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Stack{

public static void main(String[] args){
    //create a hashmap
    HashMap<Integer, String> map =  new HashMap<Integer,String>();

    //populate with dummy out-game entries
    for(int i = 0; i < 8;i++){
        map.put(i, "OUT-GAME");
    }

    // add the last two with in-game value
    map.put(8, "IN-GAME");
    map.put(9, "IN-GAME");

    //declare an iterator on map
    Iterator it = map.entrySet().iterator();

    //number of time "in-game" is encountered
    int check = 0;

    //while the iterator has  more to go
    while(it.hasNext()){

        //get the key-value pairs and print them just for checking 
        //the entries

        Map.Entry pair = (Map.Entry<Integer,String>) it.next();
        System.out.println(pair.getKey() + " " +  pair.getValue());

        //if the value "in-game" is encountered increment the check by 1

        if(pair.getValue().equals("IN-GAME")){
            System.out.println("We have a player in game");
            check++;
        }

        //if "in-game" is encountered more than once, then print an alarm

        if(check > 1){
            System.out.println("More than 1 player in game. There something wrong");
        }
    }

    //if there only one player with "in-game", inform me

    if(check == 1){
        System.out.println("We have exactly one player in the game");
    }
}
}

, "in-game".

0

If you want to check if there are any duplicate values, the simplest solution is to reset it in the set and compare the size of the result with the original:

boolean hasDuplicates = new HashSet<>(map.values()).size() < map.size();
0
source

Source: https://habr.com/ru/post/1682161/


All Articles