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 String
is extracted. The other list contains String
literals.
One often finds the following code snippet to accomplish this task (see this answer):
List<Person> people = getPeopleFromDatabasePseudoMethod();
List<String> expectedValues = Arrays.asList("john", "joe", "bill");
assertTrue(people.stream().map(person -> person.getName()).collect(Collectors.toList()).containsAll(expectedValues));
The Person
class is defiend as:
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
// other getters and setters
}
In the example above, the list of persons (or people) is transformed to a list of Strings using Java 8 techniques and the comparision is done in the old-fashioned way.
Now I wonder, if there is a more direct or more efficient way of doing the comparison using other Java 8 statements, for example allMatch()
or some Predicate<T>
or something else.
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<Person> people = getPeopleFromDatabasePseudoMethod();
List<String> 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<String> 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<String> 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.