How to get index of a sub list from another list?

The java.util.Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

Collections.indexOfSubList() method will returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. Syntax: public static int indexOfSubList(List source, List target)

Example

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Test { 
    public static void main(String a[]){         
        List<String> list1 = new ArrayList<String>();
        list1.add("ajay");
        list1.add("amit");
        list1.add("vikas");
        list1.add("anil");
        List<String> list2 = new ArrayList<String>();
        list2.add("vikas");
        list2.add("anil");
        System.out.println("Index of list2: "+Collections.indexOfSubList(list1, list2));
    }
}

Output

Index of list2: 2

Java Collections class examples

Please follow and like us:
Content Protection by DMCA.com