How to assert on the existence of a certain value in an array

Viewed 37
class Configuration { String name, String type }
Configuration[] configurations = ..

I want to put a assert check to see if the array contains a certain value in the name field (say name="Any"). We are currently looping the array to check this, what would be an elegant way

3 Answers

Using the Streams API:

assertTrue(Arrays.stream(configurations).anyMatch(c -> "Any".equals(c.name));

Another slight variation using the Streams API and a method reference:

assertTrue(Arrays
    .stream(configurations)
    .map(c -> c.name)
    .anyMatch("ValueToLookFor"::equals));

Use AssertJ:

assertThat(configurations).extracting(Configuration::getName).contains("Any");

or you may prefer:

assertThat(configurations).anyMatch(c -> "Any".equals(c.name));
Related