我想弄清楚的是你如何检查一个hashmap(在我的情况下可能有任意数量的键)是否只有一个特定值分配给它。我在这里努力解释这个问题。
如果我有一个带有10个键的hashmap(每个游戏中的玩家都被指定拥有一个游戏状态,取决于他们所处的“游戏状态”)并且只有一个玩家拥有游戏状态IN_GAME,那我该如何检查实际上只有一个Key赋值为IN_GAME,并且没有两个键具有该值?
答案 0 :(得分:3)
使用流:
Map<String, String> data = new HashMap<>();
// adding data
long count = data.values().stream().filter(v -> v.equals("IN_GAME")).count();
Count将返回地图中“IN_GAME”值的数量。
答案 1 :(得分:0)
使用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's something wrong");
}
}
//if there's only one player with "in-game", inform me
if(check == 1){
System.out.println("We have exactly one player in the game");
}
}
}
以上代码告诉您,有多个玩家拥有“游戏中”属性。
答案 2 :(得分:0)
如果要检查是否有任何重复值,最简单的解决方案是将其转储到集合中并将结果大小与原始值进行比较:
boolean hasDuplicates = new HashSet<>(map.values()).size() < map.size();