Java如何在列表中查詢子列表?

2019-10-16 22:28:43

在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