Show List

Working with arrays and lists

Arrays and lists are fundamental data structures in Groovy, providing a way to store and manipulate collections of data.

  1. Arrays: Arrays in Groovy are similar to arrays in other programming languages, and can be created using square brackets and comma-separated values:

    less
    Copy code
    def numbers = [1, 2, 3, 4, 5] println numbers[2] // outputs: 3

    Arrays in Groovy are dynamic, so you can add or remove elements from them at any time:

    bash
    Copy code
    def 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, and reduce. For example:

    java
    Copy code
    def numbers = [1, 2, 3, 4, 5] def squares = numbers.collect { it * it } println squares // outputs: [1, 4, 9, 16, 25]
  2. 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:

    css
    Copy code
    def 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, and reduce. For example:

    python
    Copy code
    def 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


  • captcha text