在Java编程中,如何在列表中查找子列表?
以下示例使用indexOfSubList()
和lastIndexOfSubList()
方法来检查列表中是否存在子列表,并查找列表中子列表的最后一次出现。
package com.yiibai;
import java.util.*;
public class FindSublist {
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));
}
}
上述代码示例将产生以下结果 -
List :[one, Two, three, Four, five, six, one, three, Four]
SubList :[three, Four]
indexOfSubList: 2
lastIndexOfSubList: 7