Groovy

Groovy Goodness: Removing Elements From a Collection

Posted on by  
Hubert Klein Ikkink

There are a lot of methods added to the Java collection classes by Groovy. For example to remove elements from a collection, and indeed modify the collection itself, we can use the removeAll and removeElement methods. With the removeAll method we define a closure with a condition that needs to be true for an element to be removed from the collection. The removeElement method is added to overcome any ambiguity with the standard overloaded remove method for collections with integer values. The remove method accepts both an Object or int value, to remove either an element or an element at the specified index. When the collection contains integer values than the argument is interpreted as index value. The removeElement method will use the remove(Object) method implementation. When the collection is a List Groovy adds the removeAt method. We need to specify the index value of the element we want to remove.

def list = ['Groovy', '=', 'gr8!']

// Groovy adds removeAll method
// to remove items from collection
// that apply to the condition we
// define in the closure.
list.removeAll { it.toLowerCase().startsWith('g') }

// All values starting with a G or g
// are now removed.
// Remember the collection we use the
// removeAll method on is changed.
assert list == ['=']

// Java 8 adds removeIf method with
// a predicate. In Groovy we can implement
// the predicate as closure.
list.removeIf { it instanceof String }

assert list.size() == 0


def values = ['Hello', 'world']

// Groovy adds removeAll(Object[])
// to remove multiple elements
// from a collection.
values.removeAll(['world', 'Hello'] as Object[])

assert values.empty


def items = [1, 2, 3]

// remove method is overloaded
// for Object and index value.
// Because Groovy wraps int to
// Integer object, the method call
// is ambiguous for Integer collections.
items.remove(1)

// We want to remove object
// Integer(1) from the list,
// but item with index 1 is removed.
assert items == [1, 3]

// Groovy adds removeElement
// as alias for remove(Object).
items.removeElement(1)

assert items == [3]

// When the collection is a List
// we can use the removeAt method
// to remove based on index value.
items.removeAt(0)

assert !items

Continue reading →

Groovy Goodness: Share Data in Concurrent Environment with Dataflow Variables

Posted on by  
Hubert Klein Ikkink

To work with data in a concurrent environment can be complex. Groovy includes GPars, yes we don't have to download any dependencies, to provide some models to work easily with data in a concurrent environment. In this blog post we are going to look at an example where we use dataflow variables to exchange data between concurrent tasks. In a dataflow algorithm we define certain functions or tasks that have an input and output. A task is started when the input is available for the task. So instead of defining an imperative sequence of tasks that need to be executed, we define a series of tasks that will start executing when their input is available. And the nice thing is that each of these tasks are independent and can run in parallel if needed.
The data that is shared between tasks is stored in dataflow variables. The value of a dataflow variable can only be set once, but it can be read multiple times. When a task wants to read the value, but it is not yet available, the task will wait for the value in a non-blocking way.

In the following example Groovy script we use the Dataflows class. This class provides an easy way to set multiple dataflow variables and get their values. In the script we want to get the temperature in a city in both Celcius and Fahrenheit and we are using remote web services to the data:

Continue reading →

Groovy Goodness: Use Closures as Java Lambda Expressions

Posted on by  
Hubert Klein Ikkink

Java 8 introduced lambda expressions we can use for example with the new Java Streams API. The Groovy syntax doesn't support the lambda expressions, but we can rely on closure coersion to use Groovy closures as Java lambda expressions in our code.

In the following sample we use the Java Streams API. Instead of lambda expressions for the filter and map methods we use Groovy closures. They are automatically transformed to lambda expressions, so it is very easy to use Java streams from Groovy code.

Continue reading →

Groovy Goodness: Combine Elements Iterable with Index

Posted on by  
Hubert Klein Ikkink

Since Groovy 2.4.0 we can get the indices from the elements in a collection with the indices method. In addition to this method we can also use the withIndex to combine an Iterable with the indices directly. The output is a List of tuples where the first item is the value of the Iterable and the second the index value. We can pass an optional argument to the withIndex which is the starting point for the index values. Another alternative is the indexed method. The indexed method returns a Map, where the key of the entry is the index value and the entry value is the Iterable value.

In the following example we use the withIndex method. The sample of the alphabet is the same as in the blog post about indices, but rewritten with the withIndex method:

Continue reading →

Groovy Goodness: Swapping Elements in a Collection

Posted on by  
Hubert Klein Ikkink

Groovy already has so many extra methods for working with collections. If we have to need to swap two elements in a collection we can use the swap method. We provide the two index values of the elements we want to swap and Groovy swaps the elements.

In the following sample we have a simple list and swap all elements by invoking the swap method two times:

Continue reading →

Groovy Goodness: Use Constructor as Method Pointer

Posted on by  
Hubert Klein Ikkink

In Java 8 we can create a constructor reference. We must use the syntax Class::new and we get a constructor reference. This syntax is not supported in Groovy, but we can use the method pointer or reference syntax .& to turn a method into a closure. We can even turn a constructor into a closure and use it everywhere where closures are allowed.

In the following sample code we have a User class with some properties. Via the User.metaClass we can get a reference to the method invokeConstructor and turn it into a method closure:

Continue reading →

Groovy Goodness: Access XML-RPC API

Posted on by  
Hubert Klein Ikkink

Recently I had to access the XML-RPC WordPress API for a small project. Luckily with Groovy we can access a XML-RPC server in a Groovy way. We need to use the Groovy XML-RPC module, which is a separate dependency. The module provides code to write a XML-RPC server, but also code to access a XML-RPC server as client. We use the class XMLRPCServerProxy in the package groovy.net.xmlrpc to act as a client to a XML-RPC API. The XMLRPCServerProxy class only needs to know the URL to access the API. All API methods are dynamically dispatched to the server, so it is very flexible.

In the following Groovy script we use the WordPress XML-RPC API to access posts:

Continue reading →

Groovy Goodness: Getting the Indices of a Collection

Posted on by  
Hubert Klein Ikkink

Since Groovy 2.4 we can use the indices property on a Collection to get the indices of the elements in the collection. We get an IntRange object as a result.

def list = [3, 20, 10, 2, 1]
assert list.indices == 0..4


// Combine letters in alphabet
// with position (zero-based).
def alphabet = 'a'..'z'
def alphabetIndices = [alphabet, alphabet.indices].transpose()
// alphabetIndices = [['a', 0], ['b', 1], ...]

// Find position of each letter
// from 'groovy' in alphabet.
def positionInAlphabet = 'groovy'.inject([]) { result, value ->
    result << alphabetIndices.find { it[0] == value }[1] + 1
    result
}

assert positionInAlphabet == [7, 18, 15, 15, 22, 25]

Continue reading →

Groovy Goodness: Pop And Push Items In a List

Posted on by  
Hubert Klein Ikkink

Groovy adds the pop and push methods to the List class. With the pop method we remove the last element of the list. And with the push method we add an element to the end of the list.

def list = ['Groovy', 'is', 'great!']

// Remove last item from list
// with pop().
assert list.pop() == 'great!'
assert list == ['Groovy', 'is']

// Remove last item
// which is now 'is'.
list.pop()

// Add new item to end of
// the list (equivalent for add()).
list.push('rocks!')

assert list == ['Groovy', 'rocks!']

Continue reading →

Groovy Goodness: Getting All But the Last Element in a Collection with Init Method

Posted on by  
Hubert Klein Ikkink

In Groovy we can use the head and tail methods for a long time on Collection objects. With head we get the first element and with tail the remaining elements of a collection. Since Groovy 2.4 we have a new method init which returns all elements but the last in a collection.

In the following example we have a simple list and apply the different methods:

Continue reading →

Groovy Goodness: Take Or Drop Last Items From a Collection

Posted on by  
Hubert Klein Ikkink

We know Groovy has a lot of nice methods for working with collections. For example in previous blog posts we have seen how to take or drop elements from a list and even with a condition. Since Groovy 2.4 we can now also use the dropRight and takeRight methods to take or drop elements from the end of the list.

In the following example we have a simple list and we use the dropRight and takeRight methods to get elements from the list:

Continue reading →

Groovy Goodness: Closure as a Class

Posted on by  
Hubert Klein Ikkink

When we write Groovy code there is a big chance we also write some closures. If we are working with collections for example and use the each, collect or find methods we use closures as arguments for these methods. We can assign closures to variables and use the variable name to reference to closure. But we can also create a subclass of the Closure class to implement a closure. Then we use an instance of the new closure class wherever a closure can be used.

To write a closure as a class we must subclass Closure and implement a method with the name doCall. The method can accept arbitrary arguments and the return type can be defined by us. So we are not overriding a method doCall from the superclass Closure. But Groovy will look for a method with the name doCall to execute the closure logic and internally use methods from the Closure superclass.

Continue reading →

shadow-left