Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if there's element in my arraylist that is not in the hashmap?

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?

like image 345
randomuser1 Avatar asked Feb 20 '19 13:02

randomuser1


2 Answers

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);
like image 153
Naman Avatar answered Sep 21 '22 11:09

Naman


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

like image 23
Lino Avatar answered Sep 22 '22 11:09

Lino