代码之家  ›  专栏  ›  技术社区  ›  Christopher Klewes

在每次迭代中指定“it”(groovy)

  •  11
  • Christopher Klewes  · 技术社区  · 16 年前

    嘿,我尝试在groovy中修剪列表中的每个字符串项

    list.each() { it = it.trim(); }
    

    我怎样才能做到这一点?

    5 回复  |  直到 16 年前
        1
  •  23
  •   sepp2k    16 年前
    list = list.collect { it.trim() }
    
        2
  •  6
  •   John Wagenleitner    16 年前

    您也可以使用排列运算符:

    def list = [" foo", "bar ", " groovy "]
    list = list*.trim()
    assert "foo" == list[0]
    assert "bar" == list[1]
    assert "groovy" == list[2]
    
        3
  •  2
  •   coobird    16 年前

    Groovy Quick Start ,使用 collect

    下面是一个使用Groovy Shell的小示例:

    groovy:000> ["a    ", "  b"].collect { it.trim() }
    ===> [a, b]
    
        4
  •  1
  •   John Stoneham    16 年前

    如果确实需要修改列表,可以使用list.eachWithIndex{item,idx->list[idx]=item.trim()}。

        5
  •  0
  •   luckykrrish    16 年前

    @sepp2k我认为这在ruby中是有效的

    list=list.collect(){it.trim();}