Problem:
How to find a first/last occurrence of sublist in Java List? As expected Java Collections API has a method for this. See the example for details.
Solution:
The following Java code demonstrates use of two similar static methods from great java.util.Collections class:
- indexOfSubList
Returns the first occurrence of sublist within a list or -1 when not found. - lastIndexOfSubList
Returns the last occurrence of sublist within a list or -1 when not found.
package com.farenda.java; import java.util.Arrays; import java.util.Collections; import java.util.List; public class CollectionsIndexOfSublist { public static void main(String[] args) { List<String> list = Arrays.asList("This is a sentence".split("")); System.out.println("Original list: " + list); findFirstAndLastOccurrence(list, Arrays.asList("i", "s")); findFirstAndLastOccurrence(list, Collections.emptyList()); findFirstAndLastOccurrence(list, Arrays.asList("uh", "oh")); } private static void findFirstAndLastOccurrence(List<String> words, List<String> sublist) { System.out.printf("The first occurrence of %s at index: %d%n", sublist, Collections.indexOfSubList(words, sublist)); System.out.printf("The last occurrence of %s at index: %d%n%n", sublist, Collections.lastIndexOfSubList(words, sublist)); } }
Result of running the code is as follows:
Original list: [T, h, i, s, , i, s, , a, , s, e, n, t, e, n, c, e] The first occurrence of [i, s] at index: 2 The last occurrence of [i, s] at index: 5 The first occurrence of [] at index: 0 The last occurrence of [] at index: 18 The first occurrence of [uh, oh] at index: -1 The last occurrence of [uh, oh] at index: -1
Note that if we are looking for empty sublist, both indexOfSubList and lastIndexOfSubList found it, but on the first and the last index accordingly.