Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of contain sublist from list java

Tags:

java

list

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]

like image 438
ductran Avatar asked Nov 26 '13 17:11

ductran


2 Answers

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.

like image 169
Holger Avatar answered Oct 13 '22 06:10

Holger


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;
}
like image 33
Mehmet Sedat Güngör Avatar answered Oct 13 '22 06:10

Mehmet Sedat Güngör