Groovy List 常用操作

1:集合克隆

  def list1 = ['a', 'b', 'c']
        def list2 = list1.clone()

2:list遍历

a:使用each进行遍历

def list = [1, 2, 3]
        list.each {
            println "Item: $it"
        }

it是是与当前元素对应的隐式参数

遍历时候使用了${}操作符。只是省略了{}

b:使用eachWithIndex进行遍历 可以打印出集合的下标和下标对应的值

 def list = ['a', 'b', 'c']
        list.eachWithIndex { it, i -> // `it` is the current element, while `i` is the index
            println "$i: $it"
        }

' it '是当前元素,而' i '是索引

c:通过将其每个元素转换为其他元素来创建一个新列表通常也很有用。由于collect方法,这个操作(通常称为映射)是在Groovy中完成的

  def list = [1, 2, 3]
       def newList =  list.collect { it * 2 }
        println(newList)

上面是将list集合通过调用collect()把list中的值*2构成一个新的集合,构成的新集合是[2,4,6]

d:使用multiply()方法 快捷语法创建一个新集合

 def list = [1, 2, 3]
       def newList =   list*.multiply(2)
        println(newList)

e:使用collect. 参数list创建一个新的集合

 def list = [0]
        def originList = [1,2,3]
        def newList = originList.collect(list) { it * 2 }
        println(newList)

查找集合中某个值

a:使用find()方法. 找到第一个元素匹配标准

  def list = [1, 2, 3]
        println(list.find { it > 1 })

这个结果是2

b:使用findAll()   找到所有匹配的元素

def list = [1, 2, 3]
        println(list.findAll{ it > 1 })

这个是[2,3]

c:使用findIndexOf()  查找第一个元素匹配标准的索引

  def strList =  ['a', 'b', 'c', 'd', 'e']
       def index =  strList.findIndexOf {
            it in ['c', 'e', 'g']
       
  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Groovy中,有几个可用的算术运算符。加法运算符(+)用于将两个操作数相加,例如2 + 3 = 5。减法运算符(-)用于从第一个操作数中减去第二个操作数,例如5 - 3 = 2。乘法运算符(*)用于将两个操作数相乘,例如2 * 8 = 16。除法运算符(/)用于将第一个操作数除以第二个操作数,例如4 / 2 = 2。取余运算符(%)用于计算两个操作数相除后的余数,例如5 % 2 = 1。 此外,Groovy还支持自增和自减运算符。自增运算符(++)用于在操作数的基础上加1,例如INT X = 12; X++;最终X的值为13。自减运算符(--)用于在操作数的基础上减1,例如INT X = 12; X--;最终X的值为12。 以上是Groovy常用的算术运算符和示例。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Groovy系列之基础语法——运算符(一)](https://blog.csdn.net/weixin_49856467/article/details/118221116)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [javaSE代码实例](https://download.csdn.net/download/zuichengyu/9555934)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值