I want to assert (using JUnit and not any other dependencies like hamcrest) if a collection contains an element with a certain property value).
I found this question How do I assert an Iterable contains elements with a certain property? using harmcrest.
One option is to override the equals
method to check only the property that I want to compare, but it is not a good solution.
Is there an elegant way to make this using JUnit 4 or should I code it and iterate through the collection to check the value?
Advertisement
Answer
Java 8’s streams and filtering could actually be quite elegant:
Collection<SomeObejct> myCollection = /* something */; boolean hasAny = myCollection.stream().anyMatch(s -> s.getProperty().equals("something")); assertTrue("Couldn't find an object with the right property", hasAny);