Java 实例 - List 截取

以下实例演示了如何使用 Collections 类的 indexOfSubList() 和 lastIndexOfSubList() 方法来查看子列表是否在列表中,并查看子列表在列表中所在的位置:

Main.java 文件

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
  5. System.out.println("List :"+list);
  6. List sublist = Arrays.asList("three Four".split(" "));
  7. System.out.println("子列表 :"+sublist);
  8. System.out.println("indexOfSubList: "
  9. + Collections.indexOfSubList(list, sublist));
  10. System.out.println("lastIndexOfSubList: "
  11. + Collections.lastIndexOfSubList(list, sublist));
  12. }
  13. }

以上代码运行输出结果为:

  1. List :[one, Two, three, Four, five, six, one, three, Four]
  2. 子列表 :[three, Four]
  3. indexOfSubList: 2
  4. lastIndexOfSubList: 7