1

I have two maps and I need to check if both has the same keys and same number of keys or not and return a boolean. I would like to use streams for this and I have got is by creating another list

mapA
.entrySet()
.stream()
.filter(entry -> mapB.containsKey(entry.getKey()))
.collect(
    Collectors.toMap(Entry::getKey, Entry::getValue));

But my question is that can I do it in a single line that would not create another list but return a boolean whether if they are same or not.

4
  • You mean true when such entries exist? Commented Mar 25, 2019 at 20:10
  • @Andronicus Yes if both maps have same keys and same number of keys then i need to return true else false Commented Mar 25, 2019 at 20:11
  • @YCF_L Thanks I would need to check if the number of keys is also same in both the maps Commented Mar 25, 2019 at 20:12
  • 1
    @YCF_L If mapA has additional keys that mapB doesn't have, containsAll will still return true. That's not what OP wants. Commented Mar 25, 2019 at 20:44

1 Answer 1

5

There's no need to use streams for this. Just obtain the maps' key sets and use equals, which is specified in Set as follows:

Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set [.]

Map<String, Integer> m1 = new HashMap<>();
m1.put("a", 10);
m1.put("b", 10);
m1.put("c", 10);

Map<String, Integer> m2 = new HashMap<>();
m2.put("c", 20);
m2.put("b", 20);
m2.put("a", 20);

System.out.println(m1.keySet().equals(m2.keySet()));  //true
Sign up to request clarification or add additional context in comments.

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.