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
true
if the given object is also a map and the two maps represent the same mappings. More formally, two mapsm1
andm2
represent the same mappings ifm1.entrySet().equals(m2.entrySet())
. This ensures that theequals
method works properly across different implementations of theMap
interface.
If you want to assert identical iteration order, you could copy both iterations into Lists and compare the lists.