[英]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. findAll
和grep
用于查找列表中的特定元素。 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. 如果只想处理列表的一部分,请使用
findAll
或grep
,它们可以在运行闭包之前过滤列表。 These, along with collect
, all return a new list. 这些以及
collect
都返回一个新列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.