Search code examples
javajunit

Assert that two LinkedHashMaps are equal with the same order in JUnit on Java 8


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?


Solution

  • 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 maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

    If you want to assert identical iteration order, you could copy both iterations into Lists and compare the lists.