I want to compare if a list is a sublist of another list
Assume I have the following lists
List<String> checkList = Arrays.asList("a", "d");
List<String> actualList = Arrays.asList("a", "b", "c", "d");
I want to check if actualList contains checkList . I can iterate each value and compare. But is there any hamcrest matcher that will do the job
For ex.
a,d should pass
a,b,c should pass
But a,e should fail
the hasItems supports the strings to be passed individually, and contains is checking for all the values, in supports an item to be present in a list. But I wanted
assertThat(actualList,containsList(checkList))
Is there any inbuilt matcher available or do I need to write custom matcher?
hasItems accepts a varargs parameter, so you can just convert your list to an array and pass it (alternatively, just declare it as an array to begin with):
final List<String> checkList = Arrays.asList("a", "d");
// final String[] checkListAsArray = new String[] { "a", "d" };
final String[] checkListAsArray = checkList.toArray(new String[checkList.size()]);
final List<String> actualList = Arrays.asList("a", "b", "c", "d");
assertThat(actualList, Matchers.hasItems(checkListAsArray));
The order of the checkList is not important.
If you swap the roles of checkList and actualList, you could also write:
assertThat(checkList, everyItem(isIn(actualList)));
This is probably more readable than:
assertTrue(actualList.stream().allMatch(checkList::contains));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With