Groovy Array Example
Table Of Contents
1. Introduction
In previous tutorials, we have mentioned about Groovy List and provided lots of examples. In this tutorial, I will show you how to use Groovy arrays. Even if array and list seems to be same, they have differences in common. For example, arrays have fixed size while lists have dynamic size that means you can add item as much as you can after initialization of the list. If you try to add item to array with a size bigger than initial size of the array after initialization, you will get MissingMethodException or ArrayIndexOutOfBoundsException. After some theory, let’s see some Groovy arrays in action.
2. Array Declaration
In Groovy, you can declare array in Java style or Groovy style. Let’s have a look at following example for array declaration.
GroovyArrayDeclaration.groovy
package com.javacodegeeks.groovy.array class GroovyArrayDeclaration { static main(args) { def birds = new String[3] birds[0] = "Parrot" birds.putAt(1, "Cockatiel") birds[2] = "Pigeon" println birds // [Parrot, Cockatiel, Pigeon] def birdArr = ["Parrot", "Cockatiel", "Pigeon"] as String[] // You say that this is an array of Strings println birdArr // [Parrot, Cockatiel, Pigeon] } }
As you can see in the example, you can declare an array with a size, and then you can put elements in different ways in Java style. In second example, the array is directly declared with initial values. Also, it has been casted to the String that means this array has elements of type String.
3. Access Array Items
In Groovy, you can access array item by using square bracket with an index ([index]
) or using getAt(index)
function. Let’s have a look at following example to see what is going on.
GroovyArrayAccessItem.groovy
package com.javacodegeeks.groovy.array class GroovyArrayAccessItem { static main(args) { def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] println birds[0] // Parrot println birds[2] // Pigeon println birds.getAt(1) // Cockatiel println birds[-1] // Pigeon println birds[-3] // Parrot } }
As you may already know, it is easy to understand the case on line 09
, line 10
and line 11
. They are simple operations to get items on specific index. What about on line 13
? Why we use negative index? It is simple, when you use negative index, it will be accessed from the end of the array with 1 based index. When you say -1
it means the first element from the end. And in same way, when you say -3
, it means third element from the end.
4. Add Item Exception
As we said earlier, If you try to add items to an array with a bigger size than the fixed length, you will get an exception as in the example below.
GroovyAddItemException.groovy
package com.javacodegeeks.groovy.array class GroovyAddItemException { static main(args) { def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] birds << "Eagle" // MissingMethodException birds.putAt(3, "Owl") // ArrayIndexOutOfBoundsException } }
On line 08
, the method << belongs to list, that is why we got MissingMethodException
. On line 10
we have exception due to overflow the size of the array wit a size 3.
5. Array Length
In Java, you can use size()
method for the list, and length
method for the arrays in order to get actual size of the object. In Groovy, it has been simplified and you can use size method for both arrays or lists. You can see simple example below.
GroovyArrayLength.groovy
package com.javacodegeeks.groovy.array class GroovyArrayLength { static main(args) { def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] println birds.length // 3 println birds.size() // 3 } }
6. Array Min & Max Value
Let say that, you have array of numbers. You can easily find the minimum and maximum value by using the min()
and max()
functions over arrays as below.
GroovyArrayMinMax.groovy
package com.javacodegeeks.groovy.array class GroovyArrayMinMax { static main(args) { def numbers = [32, 44, 12, 9, 100, 180] println numbers.max() // 180 println numbers.min() // 9 def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] println birds.max { it.size() } // Cockatiel println birds.min { it.size() } // Parrot } }
On line 09
and line 10
you can easily understand the case but, the trick on line 14
and line 15
is, the minimum and maximum value is determined by the length of the current string value. Let say that you are iterating to find minimum and maximum value, it
means current value in the array.
7. Remove Item
Removing item here is not actually removing item from array. It is something like assign the array with one item removed version to another variable. Let see it in action.
GroovyArrayRemoveItem.groovy
package com.javacodegeeks.groovy.array class GroovyArrayRemoveItem { static main(args) { def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] def birdsWithoutParrot = birds - "Parrot" println birds // [Parrot, Cockatiel, Pigeon] println birdsWithoutParrot // [Cockatiel, Pigeon] } }
As you can see on line 09
, we are using subtracting method to remove one item and assign final version to another variable. It is not removed from the original array actually as you can see on line 11
. However, you can see another array without “Parrot” on line 13
.
8. Array Ordering
If you are interacting with collections, you may need to do ordering operations time to time. For example, you may want to reverse array, or sort the array items. You can see following example to see how it looks like.
GroovyArrayOrdering.groovy
package com.javacodegeeks.groovy.array class GroovyArrayOrdering { static main(args) { def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] println birds.reverse() // [Pigeon, Cockatiel, Parrot] println birds.sort() // [Cockatiel, Parrot, Pigeon] } }
In above example, array is reversed and items printed on the screen in reverse way on line 09
. Also, array sorted in alphabetical order by using sort()
function. You can see it on line 11
9. Array Lookup
You can perform lookup operations on arrays. In following example we will reverse every item text and also we will find an item by matching a provided regex. Let’s do it.
GroovyArrayLookup.groovy
package com.javacodegeeks.groovy.array class GroovyArrayLookup { static main(args) { def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] def revertedBirds = birds.collect { it.reverse() } println revertedBirds // [torraP, leitakcoC, noegiP] def founded = birds.find { it =~ /Cockatiel/ } println founded // Cockatiel } }
On line 11
, we have iterated by using collect
function and reversed each item by using reverse()
function. Again, it
stands for the current item in the code. On line 13
, we have used find
function to find specific item by using regular expression.
10. Conversion
You can also convert array to list in Groovy easily. You can see following example for simple usage.
GroovyArrayConversion.groovy
package com.javacodegeeks.groovy.array class GroovyArrayConversion { static main(args) { def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[] def birdList = birds.toList() println birdList.class.name // java.util.ArrayList def birdsAgain = birdList as String[] println birdsAgain.class.name // [Ljava.lang.String; } }
On line 09
, we have used toList function to convert array to list. When you check the class name of birdList
you will see it is instance of java.util.ArrayList
. As you can guess, you can convert list to array. Check out line 13 and it is easily casted to array. You can check the class name on line 15
, and you will see it is [Ljava.lang.String;
11. Conclusion
To sum up, array and list has same properties in common, but there are major differences between array and list. One of the well known difference is array has fixed size and list has dynamic size in usage. If you try to add more item bigger than the array size, you will get exception. Additionally, you can perform many operations on array like list.
You can download the full source code of the project here: GroovyArrayExample
You have forgotten to show fields set to arrays. They have different syntaxes. So, the name of your article is incorrect.