user8996561 user8996561 - 3 months ago 38
Groovy Question

Groovy: Get index of all occurences of sublist from arraylist

I am new to groovy and trying to find the indexes of all sublists in a list.
I am trying to use something like Collections.indexOfSubList like in java but it gives exception saying it applies on Lists and not ArrayLists.

So I am trying to define my own function. I am finding all the indices of all the elements in the smaller list existing in the longer list and then subtracting the indices of the result array. If it comes to 1 then I am considering that index to a sublist.

I know that I have the logic a little twisted. Can somebody guide with a better and efficient way of doing this.

Below is my code:

List list1 = [1,2,3,4,5,6,1,2,3]
List list2 = [1,2]

index1 = list1.findIndexValues {
it == list2[0];

index2 = list1.findIndexValues {
it == list2[1];
println index1
println index2

result = []
for (int i = 0; i < index1.size(); i++) {
println result

Answer Source

Edit: no longer uses Collections due to new issue re: Elastic Search.

The following code traverses along the source list, creating a sublist. It checks the sublist to see if it starts with the target list. See the asserts below (e.g. the indexes are 0-based):

def listStartsWithSubList = { source, target ->
    def result = false

    if (source.size() >= target.size()) {
        result = true

        target.eachWithIndex { item, index ->
            result = result && (item == source[index])


def indexOfSubLists = { source, target ->
    def results = []

    source.eachWithIndex { item, index ->
        def tmpList = source[index..source.size()-1]
        if (listStartsWithSubList(tmpList, target)) {
            results << index


assert [1] == indexOfSubLists([1,2,3], [2,3])
assert [2] == indexOfSubLists([1,2,3], [3])
assert [] == indexOfSubLists([1,2,3], [4])
assert [0,6] == indexOfSubLists([1,2,3,4,5,6,1,2,3], [1,2])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download