zoukankan      html  css  js  c++  java
  • 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'
  • 相关阅读:
    linux 解压tgz 文件指令
    shell 脚本没有执行权限 报错 bash: ./myshell.sh: Permission denied
    linux 启动solr 报错 Your Max Processes Limit is currently 31202. It should be set to 65000 to avoid operational disruption.
    远程查询批量导入数据
    修改 MZTreeView 赋权节点父节点选中子节点自动选中的问题
    关于乱码的问题解决记录
    我的网站优化之路
    对设计及重构的一点反思
    我的五年岁月
    奔三的路上
  • 原文地址:https://www.cnblogs.com/eastson/p/2519781.html
Copyright © 2011-2022 走看看