How to check for size AND presence of some items in collections in hamcrest

I know this question is old but I still want to answer it in case someone needs explanation.

If you want to use allOf(...) just make sure nested matchers return types match. In your test case hasSize returns org.hamcrest.Matcher<java.util.Collection<? extends T>> but hasItem yields org.hamcrest.Matcher<java.lang.Iterable<? super T>>. In this case I'd recommend to use iterableWithSize(int size) where return type is Matcher<java.lang.Iterable<T>>, so you could do:

assertThat(strings, allOf( iterableWithSize(greaterThan(2)), hasItem("string two") ) );


I think the compiler is not able to sort out the generics. The following is working for me (JDK 8u102):

assertThat(strings, Matchers.<Collection<String>> allOf(
    hasSize(greaterThan(2)),
    hasItem(is("string two"))
));