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


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. More formally, returns the lowest 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.IndexOfSubList(List <?> source, List <?> target)
 *              method.
 */
public class IndexofSublist {
	public static void main(String[] args) {
		List<String> als = new ArrayList<String>();
		List<String> ald = new ArrayList<String>();
		als.add("mohan");
		als.add("karthik");
		als.add("hari");
		als.add("kamal");
		als.add("anand");
		als.add("vinodh");
		ald.add("kamal");
		ald.add("anand");
		ald.add("vinodh");
		System.out.println("List 1 : " + als);
		System.out.println("List 2 : " + ald);
		int index = Collections.indexOfSubList(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 indexOfSubList(List<?> source,List<?> target)
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. More formally, returns the lowest 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 scanning 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 first occurrence of target.
target - the list to search for as a subList of source.
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.
Since:
1.4


Related Post

Comments


©candidjava.com