Collections.indexOfSubList and lastIndexOfSubList find contiguous element sequences, not unordered membership.
Java indexOfSubList on LinkedList: find the first and last sequence
A match requires adjacency and order
Two occurrences of the same two-receipt sequence start at positions zero and two. The target is itself a list, and equals determines whether corresponding entries match. This is a small event-pattern search, not a general regex or a search over receipt substrings.
For an empty target, the first index is zero and the last index is source.size(). Treat that boundary explicitly if an empty search request should be rejected by the product. KMP is a separate algorithmic lesson for long repeated patterns.
Do not promise random-access speed
The JDK accepts any List implementation, including LinkedList. These methods report positions; later repeated get(index) calls on a LinkedList still traverse links. A production sequence-search workload needs representative input sizes and an appropriate representation.
Working program
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class ReceiptSequenceSearch {
public static void main(String[] args) {
LinkedList<String> events = new LinkedList<>(Arrays.asList("review", "approve", "review", "approve", "archive"));
List<String> target = Arrays.asList("review", "approve");
System.out.println("first=" + Collections.indexOfSubList(events, target));
System.out.println("last=" + Collections.lastIndexOfSubList(events, target));
System.out.println("empty-last=" + Collections.lastIndexOfSubList(events, Collections.emptyList()));
}
}Output
first=0
last=2
empty-last=5Costs and boundaries
A candidate match compares sequence entries and may revisit elements for repeated prefixes. The example proves positions, not a general complexity ranking against KMP or other algorithms. The returned index is not a constant-time LinkedList node handle.
Common Mistakes
- Do not confuse contiguous sequence search with containsAll.
- Do not ignore the empty-target policy.
- Do not repeatedly index a LinkedList after obtaining a position.
Read next
Java LinkedList: operations, internals and failure cases, Java LinkedList indexed loops: a hidden quadratic traversal, Java KMP substring search: reused prefix information and UTF-16 indices.
