autarch princeps autarch princeps - 1 year ago 217
Groovy Question

Jenkins Pipeline Collection method grep

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 {
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download