fork download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Map.Entry;
  4. import java.util.Objects;
  5. import java.util.Set;
  6. import java.util.stream.Collectors;
  7.  
  8. class Ideone {
  9. public static void main(String[] args) {
  10. Map<String, Object> johnDoe = new HashMap<>();
  11. johnDoe.put("name", "John Doe");
  12. Map<String, Object> johnDoesAddress = new HashMap<>();
  13. johnDoesAddress.put("street", "samplestress");
  14. johnDoesAddress.put("city", "samplecity");
  15. johnDoesAddress.put("country", "samplecountry");
  16. johnDoe.put("address", johnDoesAddress);
  17.  
  18. Map<String, Object> janeDoe = new HashMap<>();
  19. janeDoe.put("name", "Jane");
  20. Map<String, Object> janeDoesAddress = new HashMap<>();
  21. janeDoesAddress.put("street", null);
  22. janeDoesAddress.put("city", "examplecity");
  23. janeDoesAddress.put("country", "examplecountry");
  24. janeDoe.put("address", janeDoesAddress);
  25.  
  26. System.out.println(areStructuralEqual(johnDoe, janeDoe));
  27. System.out.println(areStructuralEqual(johnDoesAddress, janeDoe));
  28. System.out.println(areStructuralEqual(johnDoe, janeDoesAddress));
  29. System.out.println(areStructuralEqual(johnDoesAddress, janeDoesAddress));
  30. }
  31.  
  32. @SuppressWarnings("unhecked")
  33. public static boolean areStructuralEqual(Map<String, ?> left, Map<String, ?> right) {
  34. if (!Objects.equals(left.keySet(), right.keySet())) {
  35. return false;
  36. }
  37.  
  38. Set<String> leftKeysWithMapValues = extractAllKeysThatMapToMaps(left);
  39. Set<String> rightKeysWithMapValues = extractAllKeysThatMapToMaps(right);
  40. if (!Objects.equals(leftKeysWithMapValues, rightKeysWithMapValues)) {
  41. return false;
  42. }
  43.  
  44. for (String key : leftKeysWithMapValues) {
  45. if (!areStructuralEqual(
  46. (Map<String, ?>) left.get(key),
  47. (Map<String, ?>) right.get(key))) {
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53.  
  54. private static Set<String> extractAllKeysThatMapToMaps(Map<String, ?> map) {
  55. return map.entrySet().stream()
  56. .filter(e -> e.getValue() instanceof Map)
  57. .map(Entry::getKey)
  58. .collect(Collectors.toUnmodifiableSet());
  59. }
  60. }
Success #stdin #stdout 0.08s 34196KB
stdin
Standard input is empty
stdout
true
false
false
true