Open In App

Java Collections lastIndexOfSubList() Method with Examples

Last Updated : 28 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The lastIndexOfSubList() method of Java Collections is used in ArrayList Collection. An ArrayList is a data structure that can sequentially store data with multiple data types.

We can create an array list by using the syntax:

List<datatype> data = new ArrayList<>();    

where,

  • datatype specifies the type of elements that are stored in the list
  • data is the name of an array list

The lastIndexOfSubList() method is used to get the starting position of the last occurrence of the specified target list within the specified source list.

Syntax:

public static int lastIndexOfSubList(List<?> first, List<?> last)  

where,

  • first is the source list, which we search for the last occurrence of the last list
  • last is the target list, which we search for as a subList of the first list

Return Type: It will return the starting position of the last occurrence of the specified target list within the specified source list. It will return -1 if there are no occurrences in the given list.

Example 1:

Java program  to check source list in the last list

Java




import java.util.*;
  
public class GFG1 {
    // main method
    public static void main(String[] args)
    {
        // Create first list
        List<String> first = new ArrayList<>();
        
        // Add elements in the first list
        first.add("Python");
        first.add("c/c++");
        first.add("java");
        first.add("html");
        first.add("php");
  
        // Create last list
        List<String> last = new ArrayList<>();
        
        // Add elements in the last list
        last.add("java");
        last.add("html");
        last.add("php");
  
        // Check source list in last list  and display
        System.out.println(
            Collections.lastIndexOfSubList(first, last));
    }
}


Output

2

Example 2:

Java




import java.util.*;
  
public class GFG1 {
    // main method
    public static void main(String[] args)
    {
        // Create first list  with numbers
        List<Integer> first
            = Arrays.asList(1, 2, 3, 45, 67, 54, 45);
  
        // Create last list  with numbers
        List<Integer> last = Arrays.asList(5, 7, 8, 6, 67);
  
        // Check source list in last list  and display
        System.out.println(
            Collections.lastIndexOfSubList(first, last));
    }
}


Output

-1


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads