Java 如何验证HashMap中的值是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18389135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to verify if a value in HashMap exist
提问by Luis Lavieri
I have the following HashMap
where the key
is a String
and the value
is represented by an ArrayList
:
我有以下内容HashMap
,其中key
is aString
和 thevalue
由 an 表示ArrayList
:
HashMap<String, ArrayList<String>> productsMap = AsyncUpload.getFoodMap();
I also have another ArrayList<String> foods
implemented in my application.
ArrayList<String> foods
我的应用程序中还有另一个实现。
My question is, What would be the best way to find out if my HashMap
contains a Specific String
from my second ArrayList
?
我的问题是,从我的第二个中找出我是否HashMap
包含一个特定的最好方法是什么?String
ArrayList
I have tried without success:
我试过没有成功:
Iterator<String> keySetIterator = productsMap.keySet().iterator();
Iterator<ArrayList<String>> valueSetIterator = productsMap.values().iterator();
while(keySetIterator.hasNext() && valueSetIterator.hasNext()){
String key = keySetIterator.next();
if(mArrayList.contains(key)){
System.out.println("Yes! its a " + key);
}
}
采纳答案by Mena
Why not:
为什么不:
// fast-enumerating map's values
for (ArrayList<String> value: productsMap.values()) {
// using ArrayList#contains
System.out.println(value.contains("myString"));
}
And if you have to iterate over the whole ArrayList<String>
, instead of looking for one specific value only:
如果您必须遍历整个ArrayList<String>
,而不是仅查找一个特定值:
// fast-enumerating food's values ("food" is an ArrayList<String>)
for (String item: foods) {
// fast-enumerating map's values
for (ArrayList<String> value: productsMap.values()) {
// using ArrayList#contains
System.out.println(value.contains(item));
}
}
Edit
编辑
Past time I updated this with some Java 8 idioms.
过去我用一些 Java 8 习语更新了这个。
The Java 8 streams API allows a more declarative (and arguably elegant) way of handling these types of iteration.
Java 8 流 API 允许以更具声明性(并且可以说是优雅)的方式来处理这些类型的迭代。
For instance, here's a (slightly too verbose) way to achieve the same:
例如,这是实现相同目标的(有点过于冗长)方法:
// iterate foods
foods
.stream()
// matches any occurrence of...
.anyMatch(
// ... any list matching any occurrence of...
(s) -> productsMap.values().stream().anyMatch(
// ... the list containing the iterated item from foods
(l) -> l.contains(s)
)
)
... and here's a simpler way to achieve the same, initially iterating the productsMap
values instead of the contents of foods
:
...这是实现相同目标的更简单方法,最初迭代productsMap
值而不是内容foods
:
// iterate productsMap values
productsMap
.values()
.stream()
// flattening to all list elements
.flatMap(List::stream)
// matching any occurrence of...
.anyMatch(
// ... an element contained in foods
(s) -> foods.contains(s)
)
回答by BlackHatSamurai
You need to use the containsKey()
method. To do this, you simply get the hashMap you want the key out of, then use the containsKey
method, which will return a boolean
value if it does. This will search the whole hashMap without having to iterate over each item. If you do have the key, then you can simply retrieve the value.
您需要使用该containsKey()
方法。要做到这一点,您只需获取您想要的键的 hashMap,然后使用该containsKey
方法,boolean
如果它返回一个值。这将搜索整个 hashMap 而不必遍历每个项目。如果您确实有密钥,那么您可以简单地检索该值。
It might look something like:
它可能看起来像:
if(productsMap.values().containsKey("myKey"))
{
// do something if hashMap has key
}
Here is the link to Android
这是安卓的链接
From the Android docs:
从 Android 文档:
public boolean containsKey (Object key) Added in API level 1
Returns whether this map contains the specified key. Parameters key the key to search for. Returns
true if this map contains the specified key, false otherwise.
public boolean containsKey(对象键)在 API 级别 1 中添加
返回此映射是否包含指定的键。参数 key 要搜索的键。退货
true if this map contains the specified key, false otherwise.
回答by boxed__l
Try this
尝试这个
Iterator<String> keySetIterator = productsMap.keySet().iterator();
Iterator<ArrayList<String>> valueSetIterator = productsMap.values().iterator();
while(keySetIterator.hasNext()){
String key = keySetIterator.next();
if(valueSetIterator.next().contains(key)){ // corrected here
System.out.println("Yes! its a " + key);
}
}
回答by Josh M
If you want the Java 8 way of doing it, you could do something like this:
如果你想要 Java 8 的方式,你可以这样做:
private static boolean containsValue(final Map<String, ArrayList<String>> map, final String value){
return map.values().stream().filter(list -> list.contains(value)).findFirst().orElse(null) != null;
}
Or something like this:
或者像这样:
private static boolean containsValue(final Map<String, ArrayList<String>> map, final String value){
return map.values().stream().filter(list -> list.contains(value)).findFirst().isPresent();
}
Both should produce pretty much the same result.
两者应该产生几乎相同的结果。
回答by Bastien Aracil
Try this :
尝试这个 :
public boolean anyKeyInMap(Map<String, ArrayList<String>> productsMap, List<String> keys) {
Set<String> keySet = new HashSet<>(keys);
for (ArrayList<String> strings : productsMap.values()) {
for (String string : strings) {
if (keySet.contains(string)) {
return true;
}
}
}
return false;
}
回答by Sajal Dutta
Here's a sample method that tests for both scenarios. Searching for items in map's keys and also search for items in the lists of each map entry:
这是测试这两种情况的示例方法。在地图的键中搜索项目,并在每个地图条目的列表中搜索项目:
private static void testMapSearch(){
final ArrayList<String> fruitsList = new ArrayList<String>();
fruitsList.addAll(Arrays.asList("Apple", "Banana", "Grapes"));
final ArrayList<String> veggiesList = new ArrayList<String>();
veggiesList.addAll(Arrays.asList("Potato", "Squash", "Beans"));
final Map<String, ArrayList<String>> productsMap = new HashMap<String, ArrayList<String>>();
productsMap.put("fruits", fruitsList);
productsMap.put("veggies", veggiesList);
final ArrayList<String> foodList = new ArrayList<String>();
foodList.addAll(Arrays.asList("Apple", "Squash", "fruits"));
// Check if items from foodList exist in the keyset of productsMap
for(String item : foodList){
if(productsMap.containsKey(item)){
System.out.println("productsMap contains a key named " + item);
} else {
System.out.println("productsMap doesn't contain a key named " + item);
}
}
// Check if items from foodList exits in productsMap's values
for (Map.Entry<String, ArrayList<String>> entry : productsMap.entrySet()){
System.out.println("\nSearching on list values for key " + entry.getKey() + "..");
for(String item : foodList){
if(entry.getValue().contains(item)){
System.out.println("productMap's list under key " + entry.getKey() + " contains item " + item);
} else {
System.out.println("productMap's list under key " + entry.getKey() + " doesn't contain item " + item);
}
}
}
}
Here's the result:
结果如下:
productsMap doesn't contain a key named Apple
productsMap doesn't contain a key named Squash
productsMap contains a key named fruits
Searching on list values for key fruits..
productMap's list under key fruits contains item Apple
productMap's list under key fruits doesn't contain item Squash
productMap's list under key fruits doesn't contain item fruits
Searching on list values for key veggies..
productMap's list under key veggies doesn't contain item Apple
productMap's list under key veggies contains item Squash
productMap's list under key veggies doesn't contain item fruits
productsMap 不包含名为 Apple 的键
productsMap 不包含名为 Squash 的键
productsMap 包含一个名为fruits的键
搜索关键水果的列表值..
主要水果下的 productMap 列表包含项目 Apple
主要水果下的 productMap 列表不包含项目 Squash
关键水果下productMap的列表不包含项目水果
搜索关键蔬菜的列表值..
关键蔬菜下的 productMap 列表不包含 Apple 项
关键蔬菜下的 productMap 列表包含项目 Squash
productMap 在关键蔬菜下的列表不包含项目水果
回答by Tim
hashMap.containsValue("your value");
Will check if the HashMap contains the value
将检查 HashMap 是否包含该值