I have a Collection containing some values.
Collection<String> myList = new ArrayList<String>();
myList.add("a");
myList.add("b");
myList.add("c");
I created a Map which has some values:
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("r", "r");
myMap.put("s","m");
myMap.put("t", "n");
myMap.put("a", "o");
I want to check whether the values in the list are present as a key in the map? The way which I know using Java is to iterate through the list and check if the map contains that particular value using myMap.containsKey(). I want to know if there is anything out there using streams or for-each which saves me either lines of code or an efficient way of doing that! Thanks for thinking through it.
EDIT:
I want to store all the elements present in the myList which are not there in myMap. So my output can be a list e.g in this scenario [b,c].
Set<String> mySet = new HashSet<String>(myList);
myMap.keySet().containsAll(set);
Does this answer your question?
After your EDIT: Given the above, you can get the keys difference between two sets using the answer to one of these questions:- What is the best way get the symmetric difference between two sets in java? or Getting the difference between two sets
...whether the values in the list are present as a key in the map?
As I understand this case as you need to verify whether all the elements in the myList are present as the myMap's keys. Use the Stream::allMatch method:
myMap.keySet().stream()
.allMatch(myList::contains);
... which is the same as:
myList.keySet().containsAll(myMap);
EDIT: I want to store all the elements present in the
myListwhich are not there inmyMap. So my output can be a list e.g in this scenario [b,c].
You don't want to store all the elements in the myList since they are already there filled. You want to retain those elements using List::retainAll.
myList.retainAll(myMap.keySet());
Printing out the result of myList would produce only the keys, that have been found in the original myList and also as a key of myMap.
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