I read in groovy how to check if a list contains a sublist - stackoverflow .
I am interested if there is a way of checking whether list contains sublist, but in a given order. For example, this code will give true,
List<String> list = Arrays.asList("PRP", "VBP", "VBN", "NN", "NNS", "MD", "VB");
List<String> sublist = Arrays.asList("MD", "VB", "VBN");
System.out.println(list.containsAll(sublist));
But I want to get false back.
You can use method Collections.indexOfSubList
.
Returns the starting position of the first occurrence of the specified target list within the specified source list, or
-1
if there is no such occurrence. More formally, returns the lowest index i such thatsource.subList(i, i+target.size()).equals(target)
, or-1
if there is no such index. (Returns-1
iftarget.size()
>source.size()
.)
int index=Collections.indexOfSubList(list , sublist);
SHORT:
If Collections.indexOfSubList(list, sublist) != -1
you will have a match