joeldesante joeldesante - 3 years ago 65
Java Question

How to check the number of keys have a certain value in a hashmap

What I am trying to figure out is how do you check if a hashmap (which in my case could have any number of keys) has only one of a certain value assigned to it. I'm struggling to explain this here.

If I have a hashmap with 10 keys (each is players in a game assigned to have a gamestate depending on what "gamestate" they are in) and there is only one player with the game state IN_GAME. Then how do I check that there is in fact only one Key assigned with the value IN_GAME, and there isnt two keys with that value?

I hope that makes sense.

Answer Source

Use streams for that:

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

Count will return the number of "IN_GAME" values in your map.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download