我想弄清楚的是,如何檢查散列表(在我的情況下是否可以有任意數量的鍵)只有一個確定的分配給它的值。我在這裏努力解釋這一點。如何檢查密鑰的數量在散列圖中有一定的值
如果我有一個包含10個鍵的散列圖(每個遊戲中的玩家都分配了一個遊戲狀態,具體取決於他們所處的「遊戲狀態」),並且只有一個遊戲狀態爲IN_GAME的玩家。那麼如何檢查實際上只有一個鍵值爲IN_GAME,並且沒有兩個具有該值的鍵?
我希望這是有道理的。
我想弄清楚的是,如何檢查散列表(在我的情況下是否可以有任意數量的鍵)只有一個確定的分配給它的值。我在這裏努力解釋這一點。如何檢查密鑰的數量在散列圖中有一定的值
如果我有一個包含10個鍵的散列圖(每個遊戲中的玩家都分配了一個遊戲狀態,具體取決於他們所處的「遊戲狀態」),並且只有一個遊戲狀態爲IN_GAME的玩家。那麼如何檢查實際上只有一個鍵值爲IN_GAME,並且沒有兩個具有該值的鍵?
我希望這是有道理的。
使用流爲:
Map<String, String> data = new HashMap<>();
// adding data
long count = data.values().stream().filter(v -> v.equals("IN_GAME")).count();
計數將返回地圖的「IN_GAME」值的數量。
我已經在做這個。但是,我如何檢查是否只有一名球員有這個值分配給他們? – joeldesante
@Chai T. Rex,tnx發表評論。我修改了我的回答 –
或者'filter(「IN_GAME」:: equals)'或者'Predicate.isEqual(「IN_GAME」)' – shmosel
使用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");
}
}
}
上面的代碼告訴你,有多個玩家在「遊戲中」屬性上。
如果你想檢查是否有任何重複值,最簡單的解決方法是傾倒在一組,並比較結果的大小原文:
boolean hasDuplicates = new HashSet<>(map.values()).size() < map.size();
你有沒有考慮一個['番石榴BiMap'(https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/BiMap.html)? –
@JoeC我有點兒還在,所以我會看看。謝謝。 – joeldesante
避免此問題的一種方法是創建一個名爲'playerInGame'的變量。然後它只能容納一個玩家(或者用'null'填充零)。 –