Nov 2, 2020

2 min read

Java — Comparing Two HashMaps | Code Factory

Using Map.equals()

package com.example.java.programming;import java.util.HashMap;
import java.util.Map;
/**
* @author code.factory
*
*/
public class Test {
public static void main(String... strings) {
Map<String, String> map1 = new HashMap<>();
map1.put("Gujarat", "Ahmedabad");
map1.put("Maharastra", "Mumbai");
Map<String, String> map2 = new HashMap<>();
map2.put("Maharastra", "Mumbai");
map2.put("Gujarat", "Ahmedabad");
Map<String, String> map3 = new HashMap<>();
map3.put("Rajasthan", "Jaipur");
map3.put("Gujarat", "Ahmedabad");
System.out.println(map1.equals(map2));
System.out.println(map1.equals(map3));
}
}
true
false
package com.example.java.programming;import java.util.HashMap;
import java.util.Map;
/**
* @author code.factory
*
*/
public class Test {
public static void main(String... strings) {
Map<String, String[]> map1 = new HashMap<>();
map1.put("Gujarat", new String[] {"Ahmedabad", "Gandhinagar"});
map1.put("Maharastra", new String[] {"Mumbai", "Pune"});
Map<String, String[]> map2 = new HashMap<>();
map2.put("Maharastra", new String[] {"Mumbai", "Pune"});
map2.put("Gujarat", new String[] {"Ahmedabad", "Gandhinagar"});
System.out.println(map1.equals(map2));
}
}
false

Using the Java Stream API

package com.example.java.programming;import java.util.HashMap;
import java.util.Map;
/**
* @author code.factory
*
*/
public class Test {
public static void main(String... strings) {
Map<String, String> map1 = new HashMap<>();
map1.put("Gujarat", "Ahmedabad");
map1.put("Maharastra", "Mumbai");
Map<String, String> map2 = new HashMap<>();
map2.put("Maharastra", "Mumbai");
map2.put("Gujarat", "Ahmedabad");
Map<String, String> map3 = new HashMap<>();
map3.put("Rajasthan", "Jaipur");
map3.put("Gujarat", "Ahmedabad");
System.out.println(map1.entrySet().stream().allMatch(m -> m.getValue().equals(map2.get(m.getKey()))));
System.out.println(map1.entrySet().stream().allMatch(m -> m.getValue().equals(map3.get(m.getKey()))));
}
}
true
false
package com.example.java.programming;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author code.factory
*
*/
public class Test {
public static void main(String... strings) {
Map<String, String[]> map1 = new HashMap<>();
map1.put("Gujarat", new String[] {"Ahmedabad", "Gandhinagar"});
map1.put("Maharastra", new String[] {"Mumbai", "Pune"});
Map<String, String[]> map2 = new HashMap<>();
map2.put("Maharastra", new String[] {"Mumbai", "Pune"});
map2.put("Gujarat", new String[] {"Ahmedabad", "Gandhinagar"});
System.out.println(map1.entrySet().stream().allMatch(m -> Arrays.equals(m.getValue(), map2.get(m.getKey()))));
}
}
true