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.
issubset() function. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another.
ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
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
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