Java Basics Examples
Java Tutorial
Java Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM
|
Java Examples - Find sublist in a list
Problem Description:
How to find a sublist in a List?
Solution:
Following example uses indexOfSubList() & lastIndexOfSubList() to check whether the sublist is there in the list or not & to find the last occurance of the sublist in the list.
import java.util.*;
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five
six one three Four".split(" "));
System.out.println("List :"+list);
List sublist = Arrays.asList("three Four".split(" "));
System.out.println("SubList :"+sublist);
System.out.println("indexOfSubList: "
+ Collections.indexOfSubList(list, sublist));
System.out.println("lastIndexOfSubList: "
+ Collections.lastIndexOfSubList(list, sublist));
}
}
|
Result:
The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
SubList :[three, Four]
indexOfSubList: 2
lastIndexOfSubList: 7
|
|
|
|