0

I am trying to use the method grep from java.util.Collection inside a declarative pipeline, but it seems to have a different signature. In the script console I can execute the following simple example code, without problems:

[1,2,3,4].grep({ it == 4 })

It returns the array containing the element 4, which is what I want. When I execute similar code inside a pipeline however, it returns a Boolean, which is not only not what I want to, it doesn't even return true, when finding something, it is always false.

pipeline {
  agent {
    label 'Cloud-Ubuntu-Slave'
  }
  options {
      timestamps()
  }    
  stages {
    stage ('Debug') {
      steps {
        script {
          echo "${[1,2,3,4].grep({ it == 4 })}"
        }
     }
   }
 }

I suspect that given the pipeline context, it executes a different method named grep, rather than the one from Collection, despite the fact that the code is the same, but I haven't been able to find out why or how to change this.

What is also strange, is that I am able to execute most methods from Collection (e.g. collect) correctly.

This is obviously just a simplified example of what I'm actually doing. What I really want to do is a filter of a collection based on a lambda function returning true and false. Any alternative solution, that doesn't involve just iterating through it and manually building a new array, which is already my current, very ugly workaround, would equally be welcome.

StephenKing
  • 36,187
  • 11
  • 83
  • 112
autarch princeps
  • 170
  • 1
  • 2
  • 11
  • You could try using `${[1,2,3,4].findAll { it == 4 }}` instead, should do the same as grep in this case. If it works for you, tell me, then I make my comment an answer for you to accept. – Vampire Aug 15 '17 at 14:49
  • Yes find all works indeed. Not sure what the difference between the two is, it seems grep is more versatile, can compare to objects or regex, but since I only care about a Lambda method, findAll is just as good. Thanks @Vampire. – autarch princeps Aug 16 '17 at 06:32
  • `grep` can work with anything that has an `isCase` method. `findAll` only works with Closures. But you can use the the `isCase` method of any other object in the Closure, so you can use `findAll` in all those cases, it is just not as nicely readable as `grep`, but only slightly. Maybe it is a pretty old Groovy version where `grep` does not exist yet or something like that. – Vampire Aug 16 '17 at 08:10

1 Answers1

0

Use ${[1,2,3,4].findAll { it == 4 }} instead, it will do the same as grep in this case.

Vampire
  • 35,631
  • 4
  • 76
  • 102