In Java, Collections.indexOfSubList(source, target) searches source for the first place where all elements of target appear next to each other, in the same order. It returns the index in source where that run starts, or -1 if there is no such run.
Think of it as String.indexOf for lists: indexOf finds one element, while indexOfSubList finds a whole sequence such as [L, L, R].
A static method of the java.util.Collections utility class, available since Java 1.4. Call it on the class name, as in Collections.indexOfSubList(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Pass the list to search in, then the sequence to look for.
Java
List<Integer> data = Arrays.asList(1, 2, 3, 2, 3);
int i = Collections.indexOfSubList(data, Arrays.asList(2, 3)); // 1
int j = Collections.indexOfSubList(data, Arrays.asList(3, 1)); // -1
Call
What it does
Collections.indexOfSubList(src, target)
First start index, or -1.
Collections.lastIndexOfSubList(src, target)
Last start index, or -1.
Collections.indexOfSubList(src, emptyList)
Returns 0: an empty run "appears" at the start.
src.indexOf(x)
Finds a single element.
Elements are compared with equals (null matches null). The simple method tries each start position in turn, so in the worst case it takes about source.size() * target.size() comparisons.
Library declarations
Java
// java.util.Collections
public static int indexOfSubList(List<?> source, List<?> target)
Parameters
Parameter
Description
source
The list to search in.
target
The sequence to search for.
Return Value
Return Value
Description
int
The index in source where the first matching run begins.
-1
No matching run exists, for example when target is longer than source.