如何在Java中检查列表是否包含给定顺序的子列表 [英] How to check if a list contains a sublist in a given order in Java

查看:75
本文介绍了如何在Java中检查列表是否包含给定顺序的子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了groovy 如何检查列表是否包含子列表-stackoverflow .

I read in groovy how to check if a list contains a sublist - stackoverflow .

我感兴趣的是,是否有一种方法可以检查列表是否包含子列表,但是以给定的顺序.例如,此代码将给出 true

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));

但是我想找回 false .

推荐答案

您可以使用方法

You can use method Collections.indexOfSubList .

返回指定源列表中指定目标列表第一次出现的起始位置,如果没有出现,则返回-1. 更正式地,返回最低索引i,例如source.subList(i, i+target.size()).equals(target)-1(如果没有这样的索引). (如果target.size()> source.size(),则返回-1.)

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中检查列表是否包含给定顺序的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆