I need to check full equality of two LinkedHashMap values, including their order.
@Test
public void test(){
Map<String, Integer> actual = new LinkedHashMap<>();
actual.put("longer", 1);
actual.put("first", 1);
actual.put("thebiggest", 1);
Map<String, Integer> expected = new LinkedHashMap<>();
expected.put("thebiggest", 1);
expected.put("longer", 1);
expected.put("first", 1);
System.out.println("===expected");
expected.entrySet().stream().forEach(n->System.out.println(n.getKey()));
System.out.println("===actual");
actual.entrySet().stream().forEach(n->System.out.println(n.getKey()));
assertEquals(expected, actual);
assertTrue(expected.equals(actual));
}
All tests passed, with the output in console:
===expected
thebiggest
longer
first
===actual
longer
first
thebiggest
Everywhere in the documentation it is written that LinkedHashMap keeps the order of insertion. Than why does an assertion of two same but different ordered maps give true?
And what map should I take if equal order is important?
The definition of equals for a Map is that they have the same entry set, regardless of order.
Compares the specified object with this map for equality. Returns
trueif the given object is also a map and the two maps represent the same mappings. More formally, two mapsm1andm2represent the same mappings ifm1.entrySet().equals(m2.entrySet()). This ensures that theequalsmethod works properly across different implementations of theMapinterface.
If you want to assert identical iteration order, you could copy both iterations into Lists and compare the lists.
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