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
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 List
s 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.