I have a Hash-map of type String, ArrayList<String>. Two different keys are stored in the hash-map with list of values.
Now i have to compare the values of different keys and extract the common value. How can achieve this functionality ?
Following is the type of Hashmap that i am using:
Example List:
{Size=[43, 53, 63, 48, 58], Color=[66, 62, 65, 64, 63]}
Here is code...
private HashMap<String, ArrayList<String>> mapMatchvalues = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> map3 : mapMatchvalues.entrySet()) {
List<String> getList1 = new ArrayList<>();
getList1 = map3.getValue();
for (int i = 0; i < getList1.size(); i++) {
if (getList.contains(getList1.get(i))) {
//Print values
} else {
// Print if not matched....
}
}
}
You can use retainAll. Use new ArrayList if you don't want to effect the values in the existing lists.
List<String> common = new ArrayList<>(mapMatchvalues.get("key1"));
common.retainAll(mapMatchvalues.get("key2"));
common will contain the matching elements from the lists.
If you have multiple entries in the map you can loop over it
// initialize the common list with List
List<String> common = new ArrayList<>(mapMatchvalues.entrySet().iterator().next().getValue());
for (List<String> list : mapMatchvalues.values()) {
common.retainAll(list);
}
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