简体   繁体   English

遍历将闭包传递给过程元素的列表-Groovy

[英]Traversing a list passing a closure to process elements - groovy

Which is the correct way from the below snippets? 以下片段中正确的方法是什么?

1) def list = ["a", "b", "c", "d"]
   list.findAll({println(it)})

2) def list = ["a", "b", "c", "d"]
   list.collect({println(it)})

3) def list = ["a", "b", "c", "d"]
   list.grep({println(it)})

Please advice. 请指教。

If all you are doing is printing elements, you should use each . 如果您要做的只是打印元素,则应使用each

def list = ["a", "b", "c", "d"]
list.each { println(it) }

findAll and grep are used to find specific elements in a list. findAllgrep用于查找列表中的特定元素。 collect is used to build a new collection from the elements in the given list. collect用于根据给定列表中的元素构建新的集合。

So the correct way to print all the elements is using each , which is exactly what your example is. 因此,打印所有元素的正确方法是使用each ,这恰恰是您的示例。 This is also likely the choice for when you don't care about the result of the processing. 当您不关心处理结果时,这也可能是您的选择。 If you only want to process part of the list, use findAll or grep , which can filter the list before running the closure. 如果只想处理列表的一部分,请使用findAllgrep ,它们可以在运行闭包之前过滤列表。 These, along with collect , all return a new list. 这些以及collect都返回一个新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM