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

前端 未结 3 1152
情深已故
情深已故 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 17:01

    Your question’s code does not reflect what you describe in the comments. In the comments you say that all names should be present and the size should match, in other words, only the order may be different.

    Your code is

    List people = getPeopleFromDatabasePseudoMethod();
    List expectedValues = Arrays.asList("john", "joe", "bill");
    
    assertTrue(people.stream().map(person -> person.getName())
                     .collect(Collectors.toList()).containsAll(expectedValues));
    

    which lacks a test for the size of people, in other words allows duplicates. Further, using containsAll combining two Lists in very inefficient. It’s much better if you use a collection type which reflects you intention, i.e. has no duplicates, does not care about an order and has an efficient lookup:

    Set expectedNames=new HashSet<>(expectedValues);
    assertTrue(people.stream().map(Person::getName)
                     .collect(Collectors.toSet()).equals(expectedNames));
    

    with this solution you don’t need to test for the size manually, it is already implied that the sets have the same size if they match, only the order may be different.

    There is a solution which does not require collecting the names of persons:

    Set expectedNames=new HashSet<>(expectedValues);
    assertTrue(people.stream().allMatch(p->expectedNames.remove(p.getName()))
               && expectedNames.isEmpty());
    

    but it only works if expectedNames is a temporary set created out of the static collection of expected names. As soon as you decide to replace your static collection by a Set, the first solution doesn’t require a temporary set and the latter has no advantage over it.

提交回复
热议问题