In Java, Collections.lastIndexOfSubList(source, target) finds the last place in source where the elements of target appear next to each other in the same order. It returns the index where that last run starts, or -1 if the run never appears.
It is the list version of String.lastIndexOf. Use it when the most recent occurrence matters, such as the last time a pair of events happened in a log.
A static method of the java.util.Collections utility class, available since Java 1.4. Call it on the class name, as in Collections.lastIndexOfSubList(...), 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, 1, 2, 3);
int last = Collections.lastIndexOfSubList(data, Arrays.asList(1, 2)); // 3
int none = Collections.lastIndexOfSubList(data, Arrays.asList(3, 3)); // -1
Call
What it does
Collections.lastIndexOfSubList(src, target)
Last start index, or -1.
Collections.indexOfSubList(src, target)
First start index, or -1.
Collections.lastIndexOfSubList(src, emptyList)
Returns src.size().
src.lastIndexOf(x)
Last position of a single element.
The search starts with the latest start position that still leaves room for the whole target (source.size() - target.size()) and moves toward the front, so the first match it finds is the last one in the list.
Library declarations
Java
// java.util.Collections
public static int lastIndexOfSubList(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 last matching run begins.