Search code examples
javalistcollections

How to check if a list contains a sublist in a given order in Java


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.


Solution

  • 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 that source.subList(i, i+target.size()).equals(target), or -1 if there is no such index. (Returns -1 if target.size() > source.size().)

    int index=Collections.indexOfSubList(list , sublist);
    

    SHORT:

    If Collections.indexOfSubList(list, sublist) != -1 you will have a match