Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare the ArrayList in hasmap keys

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....
             }
      }
}
like image 823
Mamta Kaundal Avatar asked Mar 02 '26 12:03

Mamta Kaundal


1 Answers

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);
}
like image 196
Guy Avatar answered Mar 05 '26 01:03

Guy