Collections static int lastIndexOfSubList(List source,List target) method Example Program

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. More formally, returns the highest index i such that source.subList(i, i+target.size()).equals(target), or -1 if there is no such index. (Returns -1 if target.size() > source.size().)

Program

```package com.candidjava;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
*
* @author karthikeyan.T
* @description the following code shows how to use
*              Collections.lastIndexOfSubList(List <?> source, List <?> target)
*              method.
*/
public class LastIndexofSublist {
public static void main(String[] args) {
List<String> als = new ArrayList<String>();
List<String> ald = new ArrayList<String>();
System.out.println("List 1 : " + als);
System.out.println("List 2 : " + ald);
int index = Collections.lastIndexOfSubList(als, ald);
System.out.println("Starting position is: " + index);
}
}```

Output

List 1 : [mohan, karthik, hari, kamal, anand, vinodh]
List 2 : [kamal, anand, vinodh]
Starting position is: 3

Explanation

public static int lastIndexOfSubList(List<?> source,List<?> target)
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. More formally, returns the highest index i such that source.subList(i, i+target.size()).equals(target), or -1 if there is no such index. (Returns -1 if target.size() > source.size().)
This implementation uses the "brute force" technique of iterating over the source list, looking for a match with the target at each location in turn.

Parameters:
source - the list in which to search for the last occurrence of target.
target - the list to search for as a subList of source.
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.
Since:
1.4

Related Post