Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two hashMap by their key

Tags:

java

hashmap

map

I have two HashMap. I need to join the two hashMap by their key.

Map<String, String> firstMap = new HashMap<String, String>();
Map<String, String> secondMap = new HashMap<String, String>();
firstMap= [{K1,V1},{K2,V2}]
secondMap= [{K2,V2},{K3,V3}]

I need my third map to have

thirdMap= [{K2,V2}]

Kindly help me out. Thanks

like image 385
Amitabh Ranjan Avatar asked Dec 19 '22 12:12

Amitabh Ranjan


1 Answers

This code should do what you need:

Map<String, String> thirdMap = new HashMap<String, String>();

for (String key : firstMap.keySet()) {
    if (secondMap.containsKey(key)) {
        thirdMap.put(key, firstMap.get(key));
    }
}
like image 172
Jens Avatar answered Jan 03 '23 00:01

Jens