Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Use Closures as Java Lambda Expressions

DZone's Guide to

Groovy Goodness: Use Closures as Java Lambda Expressions

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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.

import groovy.transform.*

/**
 * Simple class to describe
 * a Building.
 */
@Canonical
class Building {
    String name
    int floors
    boolean officeSpace
}

// Create Building objects.
def officeSpace = new Building('Initech office', 3, true)
def theOffice = new Building('Wernham Hogg Paper Company', 4, true)
def coffeeShop = new Building('Hunter Green', 1, false)

// And add to a list.
def buildings = [officeSpace, theOffice, coffeeShop]

// Create a closure which we will use 
// later in our code.
def mapBuildingName = { building -> building.name }


// Invoke Java Streams API with lambda methods,
// but we use Groovy closures.
def officeBuildingNames = 
    buildings
        .stream() // Get Java streams.
        .filter { building -> 
            building.officeSpace && building.floors > 2 
        } // 'anonymous' closure.
        .map(mapBuildingName) // Predefined closure.
        .collect()
        
assert officeBuildingNames == ['Initech office', 'Wernham Hogg Paper Company']

Code written with Groovy 2.4.3.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}