[英]How to check values in hashmap
I wanted to make a method to check if I can see if each of my piles have 6 cards in it. 我想制作一种方法来检查我是否能看到每个桩中是否有6张牌。 This is my method
这是我的方法
public boolean checkIfPileHasSixCards() {
map.put("tpile1", tpile1);
map.put("tpile2", tpile2);
map.put("tpile3", tpile2);
for (ArrayList<Card> value : map.values()) {
int size=value.size();
if(size==6) {
return true;
}
}
return false;
}
Is my logic correct, is there a more efficient way I can iterate over the values and check if each value (ArrayList) size is 6? 我的逻辑是否正确,是否有更有效的方法可以迭代值并检查每个值(ArrayList)大小是否为6?
Returning true
inside the loop is not correct - this way, your method will return true
if any list in the map has six elements, not if all of them do. 在循环内返回
true
是不正确的 - 这样,如果地图中的任何列表包含六个元素,则您的方法将返回true
,而不是所有这些元素都有 。 Instead, you should return false
if a list doesn't have six elements, and only return true
after you're done iterating the values: 相反,如果列表没有六个元素,则应返回
false
,并且只有在完成迭代值后才返回true
:
for (List<Card> value : map.values()) {
int size = value.size();
if(size != 6) {
return false;
}
}
return true;
Note, by the way, that using Java 8's stream could make this snippet a lot cleaner. 顺便提一下,使用Java 8的流可以使这个代码段变得更加清晰。 It won't be more efficient (it's still an O(n) operation in the worst case), but it will definitely be more concise:
它不会更有效(在最坏的情况下它仍然是O(n)操作),但它肯定会更简洁:
return map.values().stream().allMatch(l -> l.size() == 6);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.