Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 714
anamar Avatar asked Sep 30 '15 11:09

anamar


People also ask

How do you check if a list is a sublist?

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.

How do you check if a list of list contains a list in Java?

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.


1 Answers

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

like image 133
Jordi Castilla Avatar answered Oct 22 '22 17:10

Jordi Castilla