What You'll Learn
You'll learn how to find the starting position of a sublist within a larger list, searching from the beginning or from the end.
Finding a Sublist Within a List
Imagine you're reading a book and want to find where a specific sequence of words appears—maybe "once upon a time." You could search from the beginning to find the first occurrence, or from the end to find the last one.
The Collections.indexOfSubList and Collections.lastIndexOfSubList methods do exactly this for lists. They search for a consecutive sequence of elements within a larger list and return the starting index where that sublist begins.
How They Work
indexOfSubList(List<?> source, List<?> target) searches forward from index 0 and returns the position of the first match. If the target sublist isn't found, it returns -1.
lastIndexOfSubList(List<?> source, List<?> target) searches backward from the end and returns the position of the last match. It also returns -1 if not found.
Both methods look for an exact sequence match—order matters, and all elements must match consecutively using equals() for comparison.
Example
List<String> words = new ArrayList<>(Arrays.asList(
"the", "cat", "sat", "on", "the", "mat"
));
List<String> pattern = Arrays.asList("the", "cat");
int first = Collections.indexOfSubList(words, pattern);
// Returns 0 (first occurrence at index 0)
int last = Collections.lastIndexOfSubList(words, pattern);
// Returns 0 (same result—only one "the cat" sequence)
List<String> pattern2 = Arrays.asList("on", "the");
int position = Collections.indexOfSubList(words, pattern2);
// Returns 3 (starts at index 3)
Key Takeaway: Use Collections.indexOfSubList to find the first occurrence of a sublist and Collections.lastIndexOfSubList to find the last occurrence, both returning the starting index or -1 if not found.