Groovy

Groovy Goodness: Interleaving Elements From Collections

Posted on by  
Hubert Klein Ikkink

Groovy 5 adds the interleave method to the Iterable class. With this method you can interleave elements from two iterables. The result is a new List with elements where the first element is the first element of the first iterable and the second element the first element of the second iterable and so on. The size of the smallest collection is used to keep interleaving elements. Elements from the larger collection are ignored in the result.
If you want to have the items from the largest collection in the resulting list you can use the value true as second argument for the interleave method.

Continue reading →

Groovy Goodness: Get Next And Previous Characters

Posted on by  
Hubert Klein Ikkink

Since Groovy 1.8.2 the next and previous methods are added to the Character class. When you invoke the method next on a char or Character instance the next character the next character of the ASCII table is returned. And when you use the previous method the previous character is returned.
Groovy 5 adds an overloaded version of the next and previous method that accepts an int argument. With this argument you can specify the number of characters to skip before returning the next or previous character. For example 'a'.next(2) return 'c' and 'c'.previous(2) returns 'a'.

Continue reading →

Groovy Goodness: Grouping Iterables Using zip And zipAll

Posted on by  
Hubert Klein Ikkink

Groovy 5 adds the extension methods zip and zipAll for iterables and iterators. Using the method you can combine elements from two collections into a new collection. The new collection contains Tuple2 instances where the values come from the items at the same index from both collections. So the first item of the first collection is grouped with the first item of the second collection. The size of the resulting collection is determined by the size of the smallest collection that is zipped.
With the zipAll method you can combine iterables of different sizes and set default values for missing items. It is possible to set a default value if an item is missing from the first iterable or the second iterable.

Continue reading →

Groovy Goodness: Map Methods To Operators

Posted on by  
Hubert Klein Ikkink

Groovy supports operator overloading since the start. Operator overloading is implemented by an actual method signature that maps to an operator. For example an object with a plus method can be used with the + operator. There is a list of methods and operators available on the Groovy website.
As long as an object has a method with a name that Groovy understands the corresponding operator can be used in Groovy code. This is even true for Java objects. Since Groovy 5 you can use the groovy.transform.OperatorRename annotation on classes, methods or constructors to map other method names to the Groovy operator overloading method names. This is very useful for third-party classes that you cannot change, but still want to use simple operators in Groovy code. You can reassign a method name to the following methods so an operator can be used: plus, minus, multiply, div, remainder, power, leftShift, rightShift, rightShiftUnassigned, and, or, xor, compareTo. Suppose you use a class with an add method and want to use the + operator for this method. The following annotation can be used @OperatorRename(plus = 'add') for a method and inside the method you can use the + operator instead of the add method of the class.

Continue reading →

Groovy Goodness: Logical Implication Operator

Posted on by  
Hubert Klein Ikkink

Since Groovy 1.8.3 Groovy has an implies() method for Boolean types. Groovy 5 adds an operator ==> for this method so you have a shorter way to express a logical implication. A logical implication is a logical function that can be expressed as P ==> Q. You can read this as P implies Q or if P than Q. This expression is true in every case except when P is true, but Q is false. The following truth table shows the interpretaton of the logical implication operator:

P

Q

P ==> Q

false

true

true

false

false

true

true

true

true

true

false

false

Continue reading →

Groovy Goodness: For Loops With Index Variable

Posted on by  
Hubert Klein Ikkink

Groovy 5 adds support for using an index variable in a for-in loop. You must define an extra variable as first argument of the for loop. This variable will be used as index variable. For each iteration of the code in the for-in loop the value of this index variable is incremented by 1. You can use this value in the for loop.

Continue reading →

Groovy Goodness: Create Ascii Bar Charts

Posted on by  
Hubert Klein Ikkink

Groovy 5 adds a new utility method to create an ascii bar chart. You can use the bar method in the org.codehaus.groovy.util.StringUtil class. You can pass a value, a minimum and maximum value and optinally specify the width of the bar chart. The result is a String value consisting of a number of "blocks". A block could be whole, but also 1/8 eights of the block are used to get a nice looking bar chart. How many of these values are needed is based on the input arguments. With this method you have a nice way to format number values on a command-line.

Continue reading →

Groovy Goodness: Transform Iterable Into A Map

Posted on by  
Hubert Klein Ikkink

Groovy 5 introduced some extra overloaded methods for the collectEntries method, that can be used to transform an iterable object into a Map. You can now pass a closure or function as arguments to transform the original iterable element into the key and value for the resulting Map. It is now also possible to pass a so-called collector Map that will be used to extend with new key/value pairs.

Besides extra overloaded method signatures for collectEntries Groovy 5 also adds the new methods withCollectedKeys and withCollectedValues. With the method withCollectedKeys a closure or function can passed to create the keys for the new Map based on the elements from the iterable. The value of the key/value pair is the unchanged element. You use the method withCollectedValues to pass a closure or function to create the value for the new key/value pair in the resulting Map. The key will be the original element from the iterable.

Continue reading →

Groovy Goodness: Using NullCheck Annotation To Prevent NullPointerException

Posted on by  
Hubert Klein Ikkink

In Groovy we can apply the @NullCheck annotation to a class, constructor or method. The annotation is an AST (Abstract Syntax Tree) transformation and will insert code that checks for null values in methods or constructors. If a null value is passed to an annotated method or constructor, it will throw an IllegalArgumentException. Without the annotation we could have a NullPointerException if we try to invoke a method on the value we pass as argument. The annotation has an optional property includeGenerated which by default is false. If we set it to true then the null checks are also applied to generated methods and constructors. This is very useful if we apply other AST transformations to our class that generates additional code.

Continue reading →

Groovy Goodness: Sorting Data With GINQ

Posted on by  
Hubert Klein Ikkink

GINQ (Groovy-INtegerate Query) is part of Groovy since version 4. With GINQ we can use SQL-like queries to work with in-memory data collections. If we want to sort the data we can use orderby followed by the property of the data we want to sort just like in SQL we can use order by. By default the sort ordering is ascending and null values are put last. We can change the sort ordering by specifying in desc with the orderby clause. Or to make the ascending order explicitly we use the statement in asc. Each of asc and desc also can take an argument to specify how we want null values to be sorted. The default way is to keep null values last in the ordering. If we want to make this explicit we use nullslast as argument to asc or desc. To have null values in the sorted result first we use the argument nullsfirst.

Continue reading →

Groovy Goodness: Using Tuples

Posted on by  
Hubert Klein Ikkink

Groovy supports a tuple type. A tuple is an immutable object to store elements of potentially different types. In Groovy there is a separate Tuple class based on how many elements we want to store in the tuple. The range starts at Tuple0 and ends with Tuple16. So we can store a maximum of 16 elements in a Groovy tuple.
Each of the classes has a constructor that takes all elements we want to store. But the Tuple class also has static factory methods to create those classes. We can use the tuple method and based on how many elements we provide to this method we get the corresponding Tuple object.

Continue reading →

shadow-left