Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check a list of values present in a map

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].

like image 812
Siddharth Shankar Avatar asked May 15 '19 20:05

Siddharth Shankar


2 Answers

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

like image 160
Anusha Avatar answered Sep 27 '22 23:09

Anusha


...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 myList which are not there in myMap. 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.

like image 35
Nikolas Charalambidis Avatar answered Sep 27 '22 21:09

Nikolas Charalambidis