Skip to main content

APIzation: Replication Package

[Q#26903891][A#26904043] How to compare two Hash Maps in Java

https://stackoverflow.com/q/26903891

Hi I am working with HashMap in java and i have a scenario where i have to compare 2 HashMaps And after comparing these two hashmaps my resulting hashmap will contain the Key as a Value of First HashMap1 and Value as a Value of second HashMap2.

Answer

https://stackoverflow.com/a/26904043

Just iterate on the keys of HashMap1, and for each key, check if it's present in HashMap2. If it's present, add the values to HashMap3 :

APIzation

final Map<String, String> hm1 = new HashMap<String, String>();
hm1.put("BOF", "SAPF");
hm1.put("BOM", "SAPM");
hm1.put("BOL", "SAPL");

final Map<String, String> hm2 = new HashMap<String, String>();
hm2.put("BOF", "Data1");
hm2.put("BOL", "Data2");

final Map<String, String> hm3 = new HashMap<String, String>();

for (final String key : hm1.keySet()) {
    if (hm2.containsKey(key)) {
        hm3.put(hm1.get(key), hm2.get(key));
    }
}
package com.stackoverflow.api;

import java.util.HashMap;
import java.util.Map;

public class Human26904043 {

  public static Map checkHashMaps(
    Map<String, String> hm1,
    Map<String, String> hm2
  ) {
    final Map<String, String> hm3 = new HashMap<>();

    for (final String key : hm1.keySet()) {
      if (hm2.containsKey(key)) {
        hm3.put(hm1.get(key), hm2.get(key));
      }
    }
    return hm3;
  }
}

package com.stackoverflow.api;

import java.util.HashMap;
import java.util.Map;

/**
 * How to compare two Hash Maps in Java
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/26904043">https://stackoverflow.com/a/26904043</a>
 */
public class APIzator26904043 {

  public static void compareMaps(
    Map<String, String> hm1,
    Map<String, String> hm2
  ) throws Exception {
    final Map<String, String> hm3 = new HashMap<String, String>();
    for (final String key : hm1.keySet()) {
      if (hm2.containsKey(key)) {
        hm3.put(hm1.get(key), hm2.get(key));
      }
    }
  }
}