Groovy Goodness Notebook
Groovy Goodness Notebook
Minimum price
Suggested price
Groovy Goodness Notebook

Last updated on 2016-11-18

About the Book

In 2009 I started to write small blog posts about Groovy at Messages from mrhaki. The posts contained code samples of cool Groovy features I just didn't want to forget. The blog posts turned out to be a useful resource for people learning and using Groovy in their every day programming.

The Groovy Goodness Notebook contains the blog posts about Groovy previously mentioned on my blog. The posts have been edited slightly so they can be used for the book. The book gives a broad overview of all the great features we can find in the Groovy language.

Updated on February 1st 2016 to include the following new subjects:

  • Inspect Method Returns Nicely Formatted Object Values
  • Operator Overloading in Reverse
  • Removing Elements From a Collection
  • Change Directory For Saving Dependencies Grape
  • See More Info About Downloading With Grape
  • Exclude Transitive Dependencies With Grape
  • IntelliJ IDEA Intentions For String Values
  • Turn Map Into Class With IntelliJ IDEA
  • Turn Method Parameters Into Named Map Arguments With IntelliJ IDEA
  • Defining Public Accessible Constant Fields
  • Customise Groovydoc Output With Gradle
  • Customising The Groovy Compiler

The book categorizes the posts into the following sections:

  • Syntax
  • Operators
  • Numbers
  • Strings
  • Regular Expressions
  • Dates
  • Lists, Ranges and Arrays
  • Maps
  • Closures
  • SQL
  • Files, Reades, Writers and URls
  • XML and JSON
  • AST transformations
  • Metaprogramming
  • DSL and Builder Support
  • Scripts
  • Testing
  • Miscellaneous

About the Author

Hubert Klein Ikkink
Hubert A. Klein Ikkink (mrhaki)

Hello. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write software, like Pixar makes movies, BMW makes cars, Bang & Olufsen makes audio and TV systems and Apple makes computers and devices: clean, elegant, user-centered and high quality.

My name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am known as Mr. Haki or mrhaki for short.

In 2009 I started writing blog posts about Groovy with the name Groovy Goodness. These posts contain small snippets of code explaining core and exotic features of the Groovy language.

Bundles that include this book

Groovy Goodness Notebook
Grails Goodness Notebook
Gradle Goodness Notebook
Suggested Price
Bundle Price
Groovy Goodness Notebook
Gradle Goodness Notebook
Suggested Price
Bundle Price
Groovy Goodness Notebook
Grails Goodness Notebook
Suggested Price
Bundle Price

Table of Contents

  • About Me
  • Introduction
  • Syntax
    • Default Imports
    • Semicolons are Optional
    • Optional return Keyword
    • Automatic Return Value Casting
    • Static Imports
    • Optional Parenthesis
    • Check for Object Equality
    • Using def to Define a Variable
    • Using Lists and Maps As Constructors
    • Parameters with Default Values
    • Named Parameters are Converted to Map
    • Use a Map as Interface Implementation
    • MultiMethods or Multiple Dispatch
    • Multiple Overloaded Operator Methods for Nice API
    • Operator Overloading in Reverse
    • Exception Handling
    • The With Method
    • The Switch Statement
    • Use Map in Switch Statement
    • Tell the Groovy Truth
    • We Can Handle the Truth
    • Groovy Truth for Simple Type Arrays
    • Boolean Implications
    • The as Keyword
    • Define Your Own Type Conversion
    • Using Project Coin Features Also With Older Java Versions
    • Getting and Setting Properties
    • GroovyBeans: the Simpler JavaBeans
    • Powerful Assert
    • Multiple Assignments
    • Multiple Assignments Revisited
    • Turn Methods into Closures
    • Use Keywords as Method Names
    • Chaining Traits
    • Implementing Traits at Runtime
    • Using Implicit call() Method
    • Groovy Mystic Expressions
    • Invoke Methods Dynamically
    • Create Class Instance Dynamically
    • Know More About a Class
    • Getting Information About Objects
    • Get Hints About Missing Methods or Properties
    • Executing String or List
    • Run Code at a Specified Time
    • Using AntBuilder
    • Add a ShutdownHook
    • Use a Class by Proxy
    • Defining Public Accessible Constant Fields
  • Operators
    • Safe Navigation to Avoid NullPointerException
    • The Elvis Operator ?:
    • The Spaceship Operator
    • The Spread-Dot Operator
    • The Spread Operator
    • Are You In? (Membership Operator)
    • Is Object in Class Hierarchy
  • Numbers
    • BigDecimal
    • Round and Truncate Decimal Values
    • Integer Divisions
    • Make a Number Absolute
    • Raising the Power of Numbers
  • Strings
    • String.multiply()
    • ‘String’, “Strings”, /Strings/ and GStrings
    • New Dollar Slashy Strings
    • Get to Know More About a GString
    • Check if String is a Number
    • What Character Are You?
    • Access Strings with Subscript Operator
    • Capitalize Strings
    • Base64 Encoding
    • Check if a String Only Contains Whitespaces
    • Convert String to Boolean
    • Padding Strings
    • Working with Lines in Strings
    • Using the replaceAll Methods from String
    • Replace Characters in a String with CollectReplacements
    • Text Translation
    • Remove Parts of a String
    • Remove Part of String With Regular Expression Pattern
    • Splitting Strings
    • Get Unique Characters in a String
    • Partial Matches
    • Transform String into Enum
    • String Continuation
    • Strip Leading Spaces from Lines
    • Strip Leading Spaces from Lines with Margin
    • Formatted Strings with sprintf
    • Expand or Unexpand Space or Tab Delimited Text
    • Normalize and Denormalize Linefeeds and Carriage Returns
    • Converting Byte Array to Hex String
    • GString as Writable
    • Closure as Writable
  • Regular Expressions
    • Using Regular Expression Pattern Class
    • Matchers for Regular Expressions
  • Dates
    • Working with Dates
    • Setting Date and Calendar Values with Subscript Operators
    • Convert Date to java.sql.Timestamp
    • Convert Date to Calendar
    • Format Dates with TimeZone
    • Parse Date.toString() Value
    • Use the set Method to Define a Date or Calendar Value
    • Create New Date from Old Date with Updates
    • Create New Date or Calendar from Existing and Set Property Value
    • Clear Time Portion of a Date
    • Date and Time Durations and the TimeCategory
    • Loop Through Date and Calendar Ranges
  • List, Ranges and Arrays
    • Create Elements in Collection Definition
    • Finding Data in Collections
    • Find First Non-Null Result From a Closure
    • Find Non-Null Results After Transformation in a Collection
    • Find Elements Matching Groovy Truth
    • Removing Elements From a Collection
    • Use Ranges as Subscript Operators
    • Use Strings as Subscript Operator
    • Using the Subscript Operator on Iterators
    • Looping in Different Ways
    • Keep Your Values in Ranges
    • Getting the Tail of a List
    • Getting Head And Tail From an Array of Objects
    • Getting the First and Last Element of an Iterable
    • Getting All But the Last Element in a Collection with Init Method
    • Take and Drop Items from a List
    • Drop or Take Elements with Condition
    • Take Or Drop Last Items From a Collection
    • Getting the Indices of a Collection
    • Combine Elements Iterable with Index
    • Pop And Push Items In a List
    • Apply Method to All Elements in a List
    • Apply Closure to All Element in a Collection with collect
    • Use Collect with Initial Collection Value
    • Transform Collection to a Map with collectEntries
    • Transform Items into a Collection with collectMany
    • Collect on Nested Collections
    • Recursively Collect Elements
    • Join Elements to a String
    • Using the Inject Method
    • Using the GroupBy Method
    • GroupBy with Multiple Closures
    • Removing Duplicate Elements in a Collection
    • Sort or Remove Duplicates without Changing the Original Collection
    • New Methods to Sort and Remove Duplicates From Collection
    • Using the OrderBy Comparator
    • GroovyCollections Utility Class
    • Splitting with Closures
    • Intersect Collections
    • Collate a List into Sub-lists
    • Getting All Subsequences of a List
    • Looping Through Each Permutation in a Collection
    • Counting the Items in a List
    • Count Occurrences in a Collection or Map
    • Getting the Sum of Items in a Collection
    • Sum the Values in a Object Array
    • Represent a List as String
    • Create a List with Default Values
    • Add Items to a List at Specified Position
    • Working with Arrays
    • See if List and Object Array are Equal
    • Convert Collection to Set with Only Unique Elements
    • See if Sets are Equal
    • Immutable Collections
    • Observable Map and List
    • Enhancements for Iterable Implementations
    • Swapping Elements in a Collection
  • Maps
    • Check if Maps are Equal
    • Sorting a Map
    • Turn a List into a Map
    • Complex Keys in Maps
    • Use inject Method on a Map
    • Intersect Maps
    • Subtracting Map Entries
    • Process Map Entries in Reverse
    • Getting a Submap from a Map
    • Grouping Map Elements
    • Get Value from Map or a Default Value
    • Map with Default Values
    • Determine Min and Max Entries in a Map
    • Represent Map As String
    • Turn A Map Or List As String To Map Or List
  • Closures
    • Passing Closures to Methods
    • Closure Arguments
    • Add Some Curry for Taste
    • New Ways to Curry
    • Implicit Closure Coercion
    • Return Closure From Another Closure or Method
    • Chain Closures Together with Closure Composition
    • Recursion with Closure Trampoline Capability
    • Cache Closure Results with Memoization
    • Info About Closure Parameters
    • Setting a Closure’s Delegate
    • Invoke Anonymous Closure
    • Implicit Method doCall in Closure
    • Closure as a Class
    • Use Closures as Java Lambda Expressions
    • Use Constructor as Method Pointer
  • SQL
    • Groovy SQL
    • Groovy SQL DataSet
    • Using Named (Ordinal) Parameters with Groovy SQL
    • Access ResultSetMetaData with Groovy SQL
    • Paging Support in Groovy SQL
  • Files, Readers, Writers and URLs
    • Working with Files
    • Working on Files or Directories (or Both) with FileType
    • Finding Files with FileNameFinder
    • Delete Non-empty Directory Recursively with File
    • Traversing a Directory
    • Creating Files And Directories With Nice DSL Using FileTreeBuilder
    • Calculating Directory Size
    • Extra Methods for NIO Path
    • withReader and withWriter
    • Transforming Reader Input to Writer Output
    • Append Values to Appendable Objects
    • Apply Read and Write Locking
    • Reading URL Content
    • Use Connection Parameters to Get Text From URL
  • XML and JSON
    • Pretty Print XML
    • Creating XML with MarkupBuilder
    • Refactor XML Creation with StreamingMarkupBuilder
    • Reading XML
    • Type Conversion Using GPathResult When Reading XML
    • Change XML Structure
    • Getting Groovy with DOM
    • Nested Templates with MarkupTemplateEngine
    • Use Custom Template Class with MarkupTemplateEngine
    • Using Layouts with MarkupTemplateEngine
    • Parse JSON with JsonSlurper
    • Relax… Groovy Will Parse Your Wicked JSON
    • Build JSON with JsonBuilder and Pretty Print JSON Text
    • Streaming JSON with StreamingJsonBuilder
  • AST transformations
    • Newify to Create New Instances
    • Create a Singleton Class
    • Inject Logging Using Annotations
    • Customise Log AST Annotations
    • Easy toString Creation for Our Classes
    • Customize ToString Creation
    • Tuple Constructor Creation
    • Generate equals and hashcode Methods with EqualsAndHashCode Annotation
    • Inherit Constructors From Parent Classes
    • Canonical Annotation to Create Mutable Class
    • Make Class Cloneable With @AutoClone
    • Combining Annotations with AnnotationCollector
    • Change Scope Script Variable with Field Annotation
    • Add Java-style Listener Support with ListenerList Annotation
    • Lazy Initialization of Properties
    • Making a Class Immutable
    • Create CopyWith Method with Immutable Annotation
    • Synchronized Annotation for Synchronizing Methods
    • Create Indexed Property Getter and Setter Methods
    • Bound and Constrained Properties in GroovyBeans
    • Delegate to Simplify Code
    • Choose Which Delegated Methods to Use
    • Cache Methods Invocations with Memoize Annotation
    • Using Package Scoped Methods, Fields and Classes
    • Use Builder AST Transformation for Fluent API
    • Using Builder to Create Fluent API for Other Classes
    • @Builder Definition with Extra Type Checks
    • More Efficient Tail Recursion With TailRecursive Annotation
    • Use Sortable Annotation to Make Classes Comparable
  • Metaprogramming
    • Use Categories to Add Functionality to Classes
    • Use a Category and Get a Return Value
    • Mixin Functionality to Classes
    • Apply Mixin to Object Instances
    • Add Methods Dynamically to Classes with ExpandoMetaClass
    • Create Dynamic Methods
    • A Bit of metaClass DSL
    • Adding or Overriding Methods with ExpandoMetaClass
    • Override getProperty Method with Dynamic Groovy
    • Implementing MetaClass Methods with Same Name but Different Arguments
    • Add Static Methods with MetaClass to Classes
    • Override and Use Old Implementation with Dynamic Methods
    • Add Methods to Interfaces with ExpandoMetaClass
    • Expando as Dynamic Bean
    • Check If Method or Property is Available
    • Intercept Methods with Interceptors
    • Magic Package to Add Custom MetaClass
    • Adding Extra Methods Using Extension Modules
  • DSL and Builder Support
    • Building Object Graphs
    • Create Simple Builders with Closures
    • Solve Naming Conflicts with Builders
    • Building a GUI with SwingBuilder
    • Command Chain Expressions for Fluid DSLs
    • Store Closures in Script Binding
    • Add Imports Transparently to Scripts with ImportCustomizer
    • Add AST Transformations Transparently to Scripts
    • Create Our Own Script Class
    • Set Script Class with BaseScript Annotation
    • BaseScript with Abstract Run Script Method
    • Set Delegating Class for Script
    • @DelegatesTo For Type Checking DSL
    • Define Compilation Customizers With Builder Syntax
    • Restricting Script Syntax With SecureASTCustomizer
  • Scripts
    • Using Groovy on the Command-Line
    • Default Groovy Script File Extensions
    • Variable Scope in Scripts
    • Grab That Dependency
    • See More Info About Downloading With Grape
    • Configuring Grape to Use Classloader
    • Use GrabResolver for Custom Repositories
    • Resolve Module Location with Grape
    • Change Directory For Saving Dependencies Grape
    • Exclude Transitive Dependencies With Grape
    • Running Groovy Scripts in Java with GroovyClassLoader
    • Simple Evaluation of Groovy Expressions in Java
    • Compiled Groovy Script is a Java Class
    • ServerSocket Scripts
    • Run Remote Scripts via URL
    • Running Scripts from a JAR Archive
    • Customize Groovy Console Visual Output
    • Using Groovy for Git Hooks
  • Testing
    • Running a Unit Test
    • Testing for Expected Exceptions
    • Create Stubs for Testing
  • IDE
    • IntelliJ IDEA Intentions For String Values
    • Turn Map Into Class With IntelliJ IDEA
    • Turn Method Parameters Into Named Map Arguments With IntelliJ IDEA
    • IntelliJ IDEA Formatting Of Closure Chains
  • Miscellaneous
    • Inspect Method Returns Nicely Formatted Object Values
    • Using Tuples
    • Parsing Commandline Arguments with CliBuilder
    • Get Properties from ReleaseInfo
    • Using ConfigSlurper with Configuration Scripts
    • Extend ConfigSlurper with Custom Environments Sections
    • Check Configuration Property Is Set In ConfigObject
    • Using the Template Engines
    • Groovlets as Lightweight Servlets
    • Access XML-RPC API
    • Customise Groovydoc Output With Gradle
    • Customising The Groovy Compiler
    • Using the ServletCategory
    • Using GroovyMBeans for Easy JMX
    • Share Data in Concurrent Environment with Dataflow Variables

The Leanpub 45-day 100% Happiness Guarantee

Within 45 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms

Free Updates. Free App. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers), EPUB (for phones and tablets), MOBI (for Kindle) and in the free Leanpub App (for Mac, Windows, iOS and Android). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

Authors, publishers and universities use Leanpub to publish amazing in-progress and completed books and courses, just like this one. You can use Leanpub to write, publish and sell your book or course as well! Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks. Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. It really is that easy.

Learn more about writing on Leanpub