The
indexOfSubList() method of
java.util.Collections class is used to return 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().)
This implementation uses the "brute force" technique of scanning over the source list, looking for a match with the target at each location in turn.
Syntax:
public static int indexOfSubList(List source, List target)
Parameters: This method takes following argument as parameter
- source - the list in which to search for the first occurrence of target.
- target - the list to search for as a subList of source.
Return Value: This method 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.
Below are the examples to illustrate the indexOfSubList() method
Example 1:
Output:
Source list: [A, B, C, D, E]
Target list: [C, D, E]
Target list starts at index: 2
Example 2: