Collections indexOfSubList() method in Java with Examples
The indexOfSubList() method of java.util.Collections class is used to return 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.
Syntax:
public static int indexOfSubList(List source, List target)
Parameters: This method takes following argument as parameter
- source – the list in which to search for the first occurrence of target.
- target – the list to search for as a subList of source.
Return Value: This method 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.
Below are the examples to illustrate the indexOfSubList() method
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
List<String> arrlistsrc = new ArrayList<String>();
List<String> arrlisttarget = new ArrayList<String>();
arrlistsrc.add( "A" );
arrlistsrc.add( "B" );
arrlistsrc.add( "C" );
arrlistsrc.add( "D" );
arrlistsrc.add( "E" );
arrlisttarget.add( "C" );
arrlisttarget.add( "D" );
arrlisttarget.add( "E" );
System.out.println( "Source list: " + arrlistsrc);
System.out.println( "Target list: " + arrlisttarget);
int index = Collections
.indexOfSubList(arrlistsrc,
arrlisttarget);
System.out.println( "Target list starts at index: "
+ index);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Source list: [A, B, C, D, E]
Target list: [C, D, E]
Target list starts at index: 2
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
List<Integer> arrlistsrc = new ArrayList<Integer>();
List<Integer> arrlisttarget = new ArrayList<Integer>();
arrlistsrc.add( 20 );
arrlistsrc.add( 30 );
arrlistsrc.add( 40 );
arrlistsrc.add( 50 );
arrlistsrc.add( 60 );
arrlisttarget.add( 40 );
arrlisttarget.add( 50 );
System.out.println( "Source list: " + arrlistsrc);
System.out.println( "Target list: " + arrlisttarget);
int index = Collections
.indexOfSubList(arrlistsrc,
arrlisttarget);
System.out.println( "Target list starts at index: "
+ index);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Source list: [20, 30, 40, 50, 60]
Target list: [40, 50]
Target list starts at index: 2
Last Updated :
20 May, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...