1:02 pm - Wednesday February 22, 2017

indexOfSubList(List source, List target)

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

Program for creating binary search index of sublist of data using

   indexOfSubList(List<?> source, List<?> target)

Example Program


import java.util.*;

public class Collections3 {

	public static void main(String args[]) {

		// create two array list objects

		ArrayList arrlistsrc = new ArrayList();

		ArrayList arrlisttarget = new ArrayList();

		// populate two lists

		arrlistsrc.add("A");

		arrlistsrc.add("B");

		arrlistsrc.add("C");

		arrlistsrc.add("D");

		arrlistsrc.add("E");

		arrlisttarget.add("C");

		arrlisttarget.add("D");

		arrlisttarget.add("E");

		// check target list in source list

		int index = Collections.indexOfSubList(arrlistsrc, arrlisttarget);

		System.out.println("Target list starts at index: " + index);

	}

}

 

Output

Target list starts at index: 2

 

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

BACK

Filed in: Z-A All Java Codes

Comments are closed.