How to join two hash cards by their key

I have two HashMap. I need to join two hash cards 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 card

thirdMap= [{K2,V2}]

Please help me. thank

+4
source share
5 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));
    }
}
+3
source
firstMap.keySet().retainAll(secondMap.keySet());

This assumes that you are allowed to modify firstMap. If not, make a copy first:

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

Then

thirdMap.keySet().retainAll(secondMap.keySet());
+2
source

Google Guava MapDifference, .

MapDifference<String, String> diff = Maps.difference(map1, map2);
+2

:

Map<String, String> firstMap = new HashMap<>();
Map<String, String> secondMap = new HashMap<>();
Map<String, String> join = new HashMap<>();

for (Entry<String, String> entry : firstMap.entrySet())
    if (secondMap.containsKey(entry.getKey())) {
        String value = secondMap.get(entry.getKey());
        if (value.equals(entry.getValue())) {
            join.put(entry.getKey(), value);
        }
    }
}
+2

firstMap = new HashMap();    secondMap = new HashMap();

 // Add everything in firstMap 
    map2.putAll(Maps.difference(firstMap , secondMap ).entriesOnlyOnLeft());
+2

All Articles