Java Collections - lastIndexOfSubList() Method
The java.util.Collections.lastIndexOfSubList() method returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
Syntax
public static int lastIndexOfSubList(List<?> source, List<?> target)
Here, T is the type of element in the collection.
Parameters
source |
Specify the list in which to search for the last occurrence of target. |
target |
Specify the list to search for as a subList of source. |
Return Value
Return the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
Exception
NA.
Example:
In the example below, the java.util.Collections.lastIndexOfSubList() method is used to find the starting position of last occurrence of specified list in a given list.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a list objects List<Integer> srclist = new ArrayList<Integer>(); List<Integer> tgtlist = new ArrayList<Integer>(); //populating srclist srclist.add(10); srclist.add(20); srclist.add(30); srclist.add(40); srclist.add(20); srclist.add(30); //populating tgtlist tgtlist.add(20); tgtlist.add(30); //printing the srclist System.out.println("srclist contains: " + srclist); //finding the starting position of tgtlist in srclist int index = Collections.lastIndexOfSubList(srclist, tgtlist); System.out.println("Target list starts at: " + index); } }
The output of the above code will be:
srclist contains: [10, 20, 30, 40, 20, 30] Target list starts at: 4
❮ Java.util - Collections