Java 8: More efficient way of comparing lists of different types?

前端 未结 3 1159
情深已故
情深已故 2021-02-05 16:31

In a unit test, I want to verify that two lists contain the same elements. The list to test is build of a list of Person objects, where one field of type Stri

3条回答
  •  心在旅途
    2021-02-05 16:52

    If the number of elements must be the same, then it would be better to compare sets:

    List people = getPeopleFromDatabasePseudoMethod();
    Set expectedValues = new HashSet<>(Arrays.asList("john", "joe", "bill"));
    assertEquals(expectedValues, 
        people.stream().map(Person::getName).collect(Collectors.toSet()));
    

    The equals method for properly implemented sets should be able to compare different types of sets: it just checks whether the contents is the same (ignoring the order of course).

    Using assertEquals is more convenient as in case of failure an error message will contain the string representation of your set.

提交回复
热议问题