CodesJava

Easy learning with example program codes

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.codesjava;
 
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

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki