Posts Tagged ‘Loop’

Loop through a list

Loop through a list using a for loop def list = [0, 1, 2, 3, 4] def total = 0 for (x in list) { total += x } assert total == 10 Loop through a list using each def list = [0, 1, 2, 3, 4] def total = 0 list.each { total += [...]

List files in a directory with a particular extension

In Groovy, the File objects traverse() function has a nameFilter attribute. def dir = new File(’/home/groovy/projects/test/src’) dir.traverse( type:FileType.FILES, nameFilter:~/.*\.groovy/ ) { println it }; This script searches the specified directory and all child directories for files ending with .groovy. If you only want to search the specified directory and not the child directories, set the [...]

List all files in a directory

Groovy’s File object provides an eachFile() method that returns both directories and files. We can then use the isFile() method to identify which of these are files. We can use the canonicalPath here to get the full path of the file. def dir = new File(’/home’) dir.eachFile { if (it.isFile()) { println it.canonicalPath } } [...]

Step through numbers

0.step(100, 10) { println it } This prints the numbers 0, 10, 20, etc. up to 90

Create a simple loop

Each of these examples print the numbers 0 to 9. Using a range with the each operator. (0..<10).each { println it } Using the times operator. 10.times { println it } Using the upto operator. 0.upto(9) { println it } Using a conventional while loop. def i = 0 while (i < 10) { println [...]