Collections.indexOfSubList in Java
February 02, 2022
Find the Java doc of Collections.indexOfSubList
method.
static int indexOfSubList(List<?> source, List<?> target)
1. The
indexOfSubList
returns the starting position of the first occurrence of the specified target list within the specified source list.
2. If target list’s starting position is at n index, the
indexOfSubList
will return n, and if target list is not available in source list, it will return -1.
3. If the size of target list is greater than source list, the
indexOfSubList
will return -1.
Example-1
CollectionsIndexOfSubList1.javapackage com.concretepage; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionsIndexOfSubList1 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); list.add(20); List<Integer> subList = new ArrayList<>(); subList.add(20); subList.add(30); int index = Collections.indexOfSubList(list, subList); System.out.println(index); // Output 1 } }
Example-2
CollectionsIndexOfSubList2.javapackage com.concretepage; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionsIndexOfSubList2 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); List<String> subList = new ArrayList<>(); subList.add("C"); subList.add("D"); int index = Collections.indexOfSubList(list, subList); System.out.println(index); // Output 2 } }
Example-3
CollectionsIndexOfSubList3.javapackage com.concretepage; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionsIndexOfSubList3 { public static void main(String[] args) { Person p1 = new Person("Ram"); Person p2 = new Person("Shyam"); Person p3 = new Person("Mahesh"); Person p4 = new Person("Shyam"); List<Person> list = new ArrayList<Person>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); List<Person> subList = new ArrayList<>(); subList.add(p1); subList.add(p2); int index = Collections.indexOfSubList(list, subList); System.out.println(index); // Output 0 } } class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } @Override public boolean equals(Object o) { return name.equals(((Person)o).name); } @Override public int hashCode() { int hash = 13; hash = (31 * hash) + (null == name ? 0 : name.hashCode()); return hash; } }