How to verify if a value in HashMap exist
Why not:
// fast-enumerating map's valuesfor (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:
// 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.
The Java 8 streams API allows a more declarative (and arguably elegant) way of handling these types of iteration.
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
:
// iterate productsMap valuesproductsMap .values() .stream() // flattening to all list elements .flatMap(List::stream) // matching any occurrence of... .anyMatch( // ... an element contained in foods (s) -> foods.contains(s) )
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.
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:
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.
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;}