I have a List<String>
in java
and it contains some Strings.
I also have a hashmap
with String
values and I would like to check if there's any element in my List that is not in the Hashmap. This is the code I wrote:
List<String> someStrings = fetchData();
if (someStrings.stream().noneMatch(s -> myHashMap.containsValue(s))) {
return false;
}
return true;
But it does not work properly. Can you help me with that?
Given that your condition is
if there's any element in my List that is not in the Hashmap
you can use anyMatch
while iterating over the list of elements to check if any of them is not present in the hashmap values.
return someStrings.stream().anyMatch(val -> !myHashMap.containsValue(val))
Or to look at it as if all elements of someStrings
are present in hashmap values
return someStrings.stream().allMatch(myHashMap::containsValue);
A similar check though could also be using containsAll
over the Collection
of values :
return myHashMap.values().containsAll(someStrings);
No need for streams, you can just use the good old Collection#removeAll()
:
Set<String> copy = new HashSet<>(someStrings);
copy.removeAll(myHashMap.values());
Now copy
will contain all the values not contained in myHashMap
. You can then do something with them (like iterating) or just call Collection#isEmpty()
to check if all are contained in the map
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With