2

I have an array of arrays.

def my_array = [[null], [10382], [11901], [null], [10386], [10385], [11901], [10386], [11901], [10386], [3], [null], [10504], [3]]

I want to find the index of the FIRST occurrence of an element, for example [3].

I am using findIndexOf.

 def index = my_array.findIndexOf { it == [3] }

However, this returns -1. I think this is the index of the element in array [3] not in array my_array. How do I get the index of the element [3] in the my_array?

1 Answer 1

4

Running this code:

def my_array = [[null],  // index  0
                [10382], // index  1
                [11901], // index  2
                [null],  // index  3
                [10386], // index  4
                [10385], // index  5
                [11901], // index  6
                [10386], // index  7
                [11901], // index  8
                [10386], // index  9
                [3],     // index 10
                [null],  // index 11
                [10504], // index 12
                [3]]     // index 13

def index = my_array.findIndexOf { it == [3] }
println "index: $index"

which is identical to your code results in:

~> groovy solution.groovy 
index: 10

~>

on java 8 and groovy 2.1.16. In other words, your code should work.

As a side note, do you really need a list of lists? As all the lists are of length one you might as well just have a list of elements directly.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I m using the Jenkins Groovy engine. There could be some differences in the dependencies. To answer your question. I don't really need it. Can I easily convert list of list into a list instead without being expensive?
list.flatten() should do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.