I have string lists look like this:
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]
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!
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.
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);
…
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.
You can change @Alessio's code like this. It also works on your cases.
public List<Interval> getIntervals(String[] parent, String[] child) {
List<Interval> intervals = new ArrayList<Interval>();
Interval interval = new Interval();
for (int i = 0, j = 0; i < parent.length; i++) {
if (child[j].equals(parent[i])) {
j++;
if (j == 1) {
interval.start = i;
}
if (j == child.length) {
interval.end = i;
intervals.add(interval);
interval = new Interval();
j = 0;
}
} else {
j = 0;
}
}
return intervals;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With