I have string lists look like this:
List parentDataList: {\"this\", \"is\", \"a\", \"test\", \"string\", \"and\", \"a\", \"test\", \"other\"}
If you want to do it manually :
public static List<Interval> getIntervals2(String[] parent, String[] child) {
List<Interval> intervals = new ArrayList<Launch.Interval>();
for (int i = 0; i < parent.length; i++) {
if (child[0].equals(parent[i])) {
Interval interval = new Interval();
interval.start = i;
intervals.add(interval);
}
}
ListIterator<Interval> iterator = intervals.listIterator();
while (iterator.hasNext()) {
Interval interval = iterator.next();
for (int j = 1, i = interval.start + 1; i < child.length; i++, j++) {
if (!child[j].equals(parent[i]))
iterator.remove();
}
if (interval.start + child.length - 1 < parent.length - 1)
interval.end = interval.start + child.length - 1;
else
iterator.remove();
}
return intervals;
}
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;
}