简体   繁体   中英

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 .

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

findAll and grep are used to find specific elements in a list. collect is used to build a new collection from the elements in the given list.

So the correct way to print all the elements is using each , which is exactly what your example is. 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. These, along with collect , all return a new list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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