从列表Java获取包含子列表的索引 [英] Get index of contain sublist from list java

查看:79
本文介绍了从列表Java获取包含子列表的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串列表如下:

 List<String> parentDataList:  {"this", "is", "a", "test", "string", "and", "a", "test", "other"} 
 List<String> child1:   {"a", "test"}
 List<String> child2:   {"this", "string"} 
 List<String> child3:   {"is", "a", "test"} 

我的期望是,我想检查父列表中是否包含序列子列表,然后基于子列表获取父列表中的开始索引和结束索引.
从上面的示例中:

My expectation is that I want to check the parent list has contain sequence children list, then get the start and end indexs in parent list base on child list.
From above example:

 Parent contain child1 list, and return the indexes: [2 - 3] and [6 - 7]
 Parent doesn't contain child2 list because it isn't sequential.
 Parent contain child3 list, and return the index: [1 - 3] 

我尝试使用List.containsAll方法,但是它不在乎列表项的顺序,因此无法从此方法获取开始和结束索引.
我正在寻找最快的方法,因为我的列表中有很多数据,而且我必须从许多输入字符串中进行搜索.
任何帮助,我们将不胜感激!

I tried using List.containsAll method, but it doesn't care the order of list item, and I can't get start and end index from this method.
I am looking for the fastest way to do this because my list has many data and I have to search from many input strings.
Any help would be appreciated!

更新:
我需要获取所有子列表的索引都包含在父列表中.例如,父级在两个位置包含child1:[2-3]和[6-7]

Update:
I need to get all index of sub lists are contained in parent list. For example, the parent contains child1 in two position: [2 - 3] and [6 - 7]

推荐答案

方法

The method Collections.indexOfSubList will give you the desired information.

返回指定源列表中指定目标列表第一次出现的起始位置,如果没有出现,则返回-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(parentDataList, child1);
…

索引间隔将从index(含)到index+child1.size()(不含).当然,除非返回的索引是-1.在后一种情况下,找不到子列表.

The index interval will be from index, inclusive, to index+child1.size(), exclusive. Unless the returned index is -1, of course. In the latter case the sublist was not found.

这篇关于从列表Java获取包含子列表的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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