Collections indexOfSubList method

In this post under Java Core, I will explain with example the pupose of Collections’ “indexOfSubList” method.

Lets say they are two lists list1 and list2.

“indexOfSubList” will search in list1 for position from where the elements of “list2” are repeated in “list1”. Once the position is found it is returned as index.

In other words, “indexOfSubList” method will check whether “list2” is a sublist or part of “list1” and if yes it returns the index whether “list2” begins in “list1”.

Below is the main example for your reference

Main class

1  package core.collection;
2  
3  import java.util.ArrayList;
4  import java.util.Collections;
5  import java.util.List;
6  
7  public class IndexOfSublistDemo {
8      public static void main(String[] args) {
9          List<Integer> integerList1 = new ArrayList<>(0);
10         integerList1.add(1);
11         integerList1.add(2);
12         integerList1.add(3);
13         integerList1.add(4);
14         integerList1.add(5);
15 
16         List<Integer> integerList2 = new ArrayList<>(0);
17         integerList2.add(3);
18         integerList2.add(4);
19 
20         List<Integer> integerList3 = new ArrayList<>(0);
21         integerList3.add(6);
22         integerList3.add(7);
23 
24         int index = Collections.indexOfSubList(integerList1, integerList2);
25         System.out.println("Is integerList2 sublist of integerList1: " + index);
26 
27         index = Collections.indexOfSubList(integerList1, integerList3);
28         System.out.println("Is integerList3 sublist of integerList1: " + index);
29     }
30 }

In the above I have create three lists “integerList1”, “integerList2”, and “integerList3”. All of them will contain elements of type Integer.

At line 24, I call “indexOfSubList” method and pass “integerList1” and “integerList2” as arguments.

The elements of “integerList2” is present in “integerList1”, so an index greater than 0 is returned.

At line 27, I again call “indexOfSubList” method and pass “integerList1” and “integerList3” as arguments.

Since the elements of “integerList3” is not present in “integerList1”, -1 is returned as index.

In this way we can use “indexOfSubList” method available on “Collections” class.

Leave a comment