0

i have this situation:

Map<String, Object> origin = new HashMap<String, Object>();
origin.put("name", "client");
origin.put("website", "https://google.com");
origin.put("settings", new HashMap<String, Object>());

Map<String, Object> other = new HashMap<String, Object>();
other.put("id", "client");
other.put("name", "client");
other.put("website", "https://google.com");
other.put("settings", new HashMap<String, Object>());


if(Objects.equals(origin, other)) {
  System.out.println("TRUE");
} else {
  System.out.println("FALSE");
}

The result is false, because origin does not contain id.

origin is always a subset of other. Both Map can contains nested maps and lists.

Is there a smart java operation which checks if the values in origin are the same in other and give true back? Or do I had to iterate through the maps and compare each key?

1
  • You have to do it manually Commented Jun 7, 2020 at 8:28

2 Answers 2

1

You mean something like : is origin is a submap of other, verifying that all mappings from origin are in other but you have missing items but don't care.

So fo each key of origin check if values are same in both Maps

boolean subMap = origin.keySet().stream().allMatch(key -> origin.get(key).equals(other.get(key)));

if (subMap) {
    System.out.println("TRUE");
} else {
    System.out.println("FALSE");
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this.

boolean result = origin.keySet().stream()
    .allMatch(key -> !other.containsKey(key) || origin.get(key).equals(other.get(key)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.