adsense


Saturday, 31 October 2015

JAVA EXAMPLES FIND SUB LIST IN A LIST PAGE 168

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA EXAMPLES FIND SUB LIST IN A LIST





Java Examples - Find sub list 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


No comments: