I have two HashMap<Integer, Question>
maps that I would like to compare. Question
in this case is a Javabean I have written.
How do I assert that both HashMap
are equal? In this scenario, equal means that both HashMap
contains exactly the same Question
bean?
If it's at all relevant, I am writing a unit test using JUnit.
We can compare two HashMap by comparing Entry with the equals() method of the Map returns true if the maps have the same key-value pairs that mean the same Entry.
Map. equals() method in Java is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.
If we want to compare hashmaps by keys i.e. two hashmaps will be equals if they have exactly same set of keys, we can use HashMap. keySet() function. It returns all the map keys in HashSet. We can compare the hashset of keys for both maps using Set.
equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation. HashMap uses equals() to compare the key to whether they are equal or not.
Using Guava you can do:
assertTrue(Maps.difference(expected, actual).areEqual());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With