Working with arrays and lists
Arrays and lists are fundamental data structures in Groovy, providing a way to store and manipulate collections of data.
Arrays: Arrays in Groovy are similar to arrays in other programming languages, and can be created using square brackets and comma-separated values:
lessCopy codedef numbers = [1, 2, 3, 4, 5] println numbers[2] // outputs: 3Arrays in Groovy are dynamic, so you can add or remove elements from them at any time:
bashCopy codedef numbers = [1, 2, 3, 4, 5] numbers << 6 println numbers // outputs: [1, 2, 3, 4, 5, 6]Arrays in Groovy also have a rich set of built-in methods for manipulating and transforming arrays, such as
sort
,map
, andreduce
. For example:javaCopy codedef numbers = [1, 2, 3, 4, 5] def squares = numbers.collect { it * it } println squares // outputs: [1, 4, 9, 16, 25]Lists: Lists in Groovy are similar to arrays, but provide a more powerful and expressive API for working with collections of data. Lists can be created using square brackets and comma-separated values:
cssCopy codedef names = ["John", "Jane", "Jim"] println names[1] // outputs: "Jane"Lists in Groovy also have a rich set of built-in methods for manipulating and transforming lists, such as
sort
,map
, andreduce
. For example:pythonCopy codedef names = ["John", "Jane", "Jim"] def upper = names.collect { it.toUpperCase() } println upper // outputs: ["JOHN", "JANE", "JIM"]
These are just a few examples of the power and flexibility of arrays and lists in Groovy. With these tools, you can write code that is easy to read, write, and maintain, making Groovy a great choice for many types of projects.
Leave a Comment