- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to find a sublist in a List using Java
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
java_collections.htm
Advertisements