Home » Java programming language

Java Collections indexOfSubList() Method with Example

Collections Class indexOfSubList() method: Here, we are going to learn about the indexOfSubList() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 03, 2020

Collections Class indexOfSubList() method

  • indexOfSubList() method is available in java.util package.
  • indexOfSubList() method is used to return the starting index of the first occurrence of the given sublist (dest) within the given full list (src).
  • indexOfSubList() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • indexOfSubList() method does not throw an exception at the time of returning index of the sublist.

Syntax:

    public static int indexOfSubList(List src, List dest);

Parameter(s):

  • List src – represents the source list in which to filter the first occurrence of the given dest.
  • List dest – represents the sublist of the given source list(src).

Return value:

The return type of this method is int, it returns the beginning index of the first occurrence of the given list(dest) within the source list (src) when it exists otherwise it return-1 when none occurrence of the element exists or list non-empty.

Example:

// Java program is to demonstrate the example
// of int indexOfSubList() of Collections

import java.util.*;

public class IndexOfSubList {
    public static void main(String args[]) {
        // Instantiate a LinkedList   
        List src_l = new LinkedList();
        List dest_l = new LinkedList();

        // By using add() method is to
        // add elements in linked list src_l
        src_l.add(10);
        src_l.add(20);
        src_l.add(30);
        src_l.add(40);
        src_l.add(50);

        // By using add() method is to
        // add elements in linked list dest_l
        dest_l.add(40);
        dest_l.add(50);

        // Display LinkedList
        System.out.println("link_l: " + src_l);
        System.out.println("dest_l: " + dest_l);

        System.out.println();

        // By using indexOfSubList() method is to
        // return the starting index of dest_l in src_l

        int index = Collections.indexOfSubList(src_l, dest_l);

        //Display index
        System.out.println("Collections.indexOfSubList(src_l,dest_l): " + index);
    }
}

Output

link_l: [10, 20, 30, 40, 50]
dest_l: [40, 50]

Collections.indexOfSubList(src_l,dest_l): 3



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.