arrays - 带数组的 Groovy 简单函数

标签 arrays function groovy

我最近开始学习 Groovy。 我不知道在 Groovy 中编写简单函数的最佳方法: 如果数组中的每个元素为正,函数必须将其乘以 2;如果为负,则函数必须除以 3。我写了一些类似java的代码:

def 数组 = [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
    }
}

最佳答案

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

或者如果您想将其分成两行:

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

您可以找到 collect 方法的文档 here 。您可能还想阅读closures .

关于arrays - 带数组的 Groovy 简单函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25197922/

相关文章:

c++ - C & C++ 中数组的动态内存分配

php - 通过 $_SESSION 从一个脚本发送到另一个脚本时数据丢失

python - 修改正则表达式

在函数内调用数组

groovy - 在 Groovy 中同时循环多个列表

java - 从 java 执行 groovy 脚本时如何阻止对某些类的访问?

php - 根据对象的属性对数组进行排序

powershell - 匿名递归函数

android - Android依赖关系无法在Groovy项目中解决

java - 将 JSONObject 获取到字符串数组值时出现问题