2

I recently started learning Groovy. I don't know best way to write simple function in Groovy: Function must multiply every element in array by 2, if it's positive, and divide by 3, if it's negative. I wrote some java's like code:

def array = [5,-8,1,4,7,3,-2,-10,5,0,4]

public void fun(){
    for(int i = 0; i < array.size; i++){
        if(array[i] > 0) array[i] = array[i] * 2;
        else array[i] = array[i] / 3
    }
}

2 Answers 2

3
def array = [5,-8,1,4,7,3,-2,-10,5,0,4].collect { it > 0 ? it * 2 : it / 3 }

Or if you want to split it into two lines:

def array = [5,-8,1,4,7,3,-2,-10,5,0,4]
array = array.collect { it > 0 ? it * 2 : it / 3 }

You can find the documentation for the collect method here. You might also want to read up on closures.

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

Comments

0

You could use Robby Cornelissen's approach with collect which will create new array. But if you would like to modify your original array (like in your current code) you can write it like below:

array.eachWithIndex { it, index -> 
    array[index] = it > 0 ? it * 2 : it / 3
}

Comments

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.