Reputation: 2397
I have a hashmap having four values a
,b
,c
,d
and list having only a
i want to see if the hashmap has the value a
and print it.
hashmap.get('data')
results a
,b
,c
,d
list l
is having a
how will i print only the value a
Upvotes: 1
Views: 5022
Reputation: 12305
Essentially you want the union of the values in the map hashmap
and those in list l
.
This should do the trick:
CollectionUtils.union(hashmap.values(), l)
This requires the Apache Commons Collections library on the classpath, which has a lot of useful features for collections.
Upvotes: 0
Reputation: 420921
If I understand your question correctly, you could solve it using the values()
method of the map, and the retainAll
method of the result:
HashMap<Integer, String> somePairs = new HashMap<Integer, String>();
somePairs.put(1, "a");
somePairs.put(2, "b");
somePairs.put(3, "c");
somePairs.put(4, "d");
List<String> list = Arrays.asList("a");
// Start off with all values in the map:
List<String> result = new ArrayList<String>(somePairs.values());
// Keep only those values present in list
result.retainAll(list);
From the API documentation on retainAll
:
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.
Upvotes: 2
Reputation: 114757
A Map stores Key-Value pairs. It offers a values()
method to get a collection of all values from the map.
So basically you have to take your own list, get the values from the hashmap and check for every item in the list if it is a map value:
public static Collection<String> contains(Map<String, String> map, List<String> list) {
Collection<String> values = map.values();
Set<String> result = new HashSet<String>();
for (String listItem:list) {
if (values.contains(listItem) {
result.add(listItem);
}
}
return result; // contains a collection of all list items that are values of the map
}
Upvotes: 2
Reputation: 4784
A Java Map (including HashMap) has a keySet() method to retieve the keys. It returns a set of keys. If you convert the List to a Set as well (by using the HashMap constructor that takes a list), you can use the Set's retainAll(...) method to obtain an intersection of values from the keys of the map and the list.
Upvotes: 0