java - 如何检查列表是否包含 Java 中给定顺序的子列表

标签 java list collections

我在 groovy 中阅读 how to check if a list contains a sublist - stackoverflow .

如果有一种方法可以检查列表是否包含子列表,但以给定的顺序,我很感兴趣。例如,此代码将给出 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));

但我想找回false

最佳答案

您可以使用方法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);

简短内容:
如果 Collections.indexOfSubList(list , sublist) =! -1 你会有一场比赛

关于java - 如何检查列表是否包含 Java 中给定顺序的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864977/

相关文章:

php - 如何为通用的、可插入的集合设计过滤器?

java - MOXy 仅编码集合中的基类成员

java - 什么会导致 RMI 方法调用间歇性失败?

java - JPA 映射实体图

android - 无法从 FirebaseMessagingService 将对象添加到自定义 ListView

c# 字母数字列表排序通过检查列表项是否包含

java - 为自定义对象列表实现 removeAll 的问题

java - 使用哈希码比较两个字符串列表是否相等?

java - 如何近似两倍?

java - 使用从其他类的方法中检索到的信息