0

I have the following array of arrays in groovy

def userList = [[name: user1, id:0, ip: 127.0.0.1], [name: user2, id:1, ip: 127.0.0.2], [name: user3, id:2, ip: 127.0.0.3]]

I am iterating over another list rows and I want to extract the entries from the above list based on index.

   rows.eachWithIndex { row, index ->
      groovy.lang.Closure idMatch = { it.id == index }
      def match = userList.findAll(idMatch)
      println(match)
   }

match is always returning empty.

The index value shows up correctly as 0,1,2 etc when I print it.

5
  • Your code works for me... Commented Jan 6, 2016 at 15:59
  • 2
    My guess is that id in your userList is not an Integer Commented Jan 6, 2016 at 16:00
  • @tim_yates do I have to use it.id.toInteger() ? Commented Jan 6, 2016 at 16:06
  • 1
    It depends what id is... Commented Jan 6, 2016 at 16:12
  • Thanks, it worked. My bad. Commented Jan 6, 2016 at 16:14

1 Answer 1

2

With Groovy 2.4 and above, one approach would be to use indices and collect() on rows instead of eachWithIndex:

def userList = [
    [name: 'user1', id:0, ip: '127.0.0.1'], 
    [name: 'user2', id:1, ip: '127.0.0.2'], 
    [name: 'user3', id:2, ip: '127.0.0.3']
]

def rows = ['foo', 'bar']

// Using indices
rows.indices.collect { index -> 
    userList.find { it.id == index } 
}

// Using indexed()    
rows.indexed().collect { index, item -> 
    userList.find { it.id == index } 
}
Sign up to request clarification or add additional context in comments.

4 Comments

indexed() method or indices is not available it seems. rows is a list and I am using grails 2.4.4
Makes sense, Grails 2.4.4 comes with Groovy 2.3.7.
With what you have in question, it should print expected results. match does print results. @user2133404
Thanks, I had to cast the id to integer.

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.