• Groovy系列 Groovy集合


    在Groovy脚本里面,集合Collection可以理解为泛指Map和List。

    List的定义:

    def list = [1, 2, 'hello', new java.util.Date()]
    assert list.size() == 4
    assert list.get(2) == 'hello'
    assert list[2] == 'hello'

    Map的定义:

    def map = ['name':'James', 'location':'London']
    assert map.size() == 2
    assert map.get('name') == 'James'
    assert map['name'] == 'James'

    collection.each(closure)

    遍历,对集合中每项都执行一次闭包,无返回值。

    [1, 2, 3].each({item -> print "${item}-"})
    //1-2-3-

    collection.collect(closure)

    收集,对集合中每项都执行一次闭包,将每项执行的结果组合成一个新的集合然后返回。

    def value = [1, 2, 3].collect { it * 2 }
    assert value == [2, 4, 6]

    collection.find(closure)

    查找,返回闭包执行结果为true的第一项。

    def value = [1, 2, 3].find { it > 1 }
    assert value == 2

    collection.findAll(closure)

    查找全部,返回闭包执行结果为true的所有项。

    def value = [1, 2, 3].findAll { it > 1 }
    assert value == [2, 3]

    collection.inject(first, closure)

    allows you to pass a value into the first iteration and then pass the result of that iteration into the next iteration and so on. This is ideal for counting and other forms of processing

    def value = [1, 2, 3].inject('counting: ') { str, item -> str + item }
    assert value == "counting: 123"
    
    value = [1, 2, 3].inject(0) { count, item -> count + item }
    assert value == 6

    collection.every(closure)

    检查每一个,如果集合中每项执行闭包结果都为true,则返回true,否则返回false。

    def value = [1, 2, 3].every { it < 5 }
    assert value
    
    value = [1, 2, 3].every { item -> item < 3 }
    assert ! value

    collection.any(closure)

    检查任一项,如果集合中有任意一项执行闭包结果为true,则返回true,否则返回false。

    def value = [1, 2, 3].any { it > 2 }
    assert value
    
    value = [1, 2, 3].any { item -> item > 3 }
    assert value == false

    collection.max()和collection.min()

    返回集合中的最大项和最小项。

    value = [9, 4, 2, 10, 5].max()
    assert value == 10
    value = [9, 4, 2, 10, 5].min()
    assert value == 2
    value = ['x', 'y', 'a', 'z'].min()
    assert value == 'a'

    collection.join(str)

    用字符串str连接集合。

    def value = [1, 2, 3].join('-')
    assert value == '1-2-3'
  • 相关阅读:
    解决ORA14098分区交换索引不匹配错误
    Oracle等待事件kfk:async disk IO
    Advanced Diagnostic using oradebug dumpvar
    shellscript 06 命令执行顺序
    Linux 备份策略
    shellscript 05 shell输入与输出
    Java video 02
    软件安装:原始码与 Tarball
    shellscript 07 正则表达式介绍
    shellscript 03 后台执行命令
  • 原文地址:https://www.cnblogs.com/eastson/p/2519781.html
Copyright © 2020-2023  润新知