Groovy Goodness Notebook
$14.99
Minimum price
$14.99
Suggested price

Groovy Goodness Notebook

Experience the Groovy programming language through code snippets

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 April 19, 2023 to include the following new subjects:

  • Using The Switch Expression
  • Get Row Number In GINQ Result Set
  • Reading TOML Configuration
  • Creating TOML Configuration With TomlBuilder
  • Closed And Open Ranges
  • Using Macros For Getting String Representation Of Variables
  • Using Macros For Getting More Information About Variables
  • Using Subscript Operator With Multiple Fields On Date Related Objects
  • Using Tuples

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

$22.98
Bought separately
$16.99
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
    • Easy Object Creation With Tap Method
    • The Switch Statement
    • Use Map in Switch Statement
    • Using The Switch Expression
    • 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
    • Add a ShutdownHook
    • Defining Public Accessible Constant Fields
    • Direct Field Access In (Super) Classes
    • Use Optional In Conditional Context
    • Check Item Is Not In A Collection With !in
  • Operators
    • Safe Navigation to Avoid NullPointerException
    • The Elvis Operator ?:
    • The Elvis Assignment Operator
    • The Spaceship Operator
    • The Spread-Dot Operator
    • The Spread Operator
    • Are You In? (Membership Operator)
    • Is Object in Class Hierarchy
    • Check Object Instances Are The Same With === Operator
    • Using !instanceof Operator
    • Safe Index Based Access For Lists, Arrays and Maps
    • Using The Call Operator ()
  • Numbers
    • BigDecimal
    • Round and Truncate Decimal Values
    • Truncate And Round BigDecimal Values
    • Integer Divisions
    • Make a Number Absolute
    • Raising the Power of Numbers
  • Strings
    • Turn Methods into Closures
    • 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
    • Uncapitalize Strings
    • Base64 Encoding
    • Check if a String Only Contains Whitespaces
    • Convert String to Boolean
    • Padding Strings
    • Working with Lines in Strings
    • Getting Parts Of A String Enclosed By 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
    • Taking Or Dropping Number Of Characters From A String
    • 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
    • Base64 URL and Filename Safe Encoding
    • Calculate MD5 And SHA Hash Values
    • 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
    • Using Subscript Operator With Multiple Fields On Date Related Objects
  • 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
    • Use Range By Method To Set Steps Between Numbers
    • Closed And Open Ranges
    • Using String Values In Ranges
    • 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 All Init And Tail Values Recursively
    • 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
    • Remove Last Item From List Using RemoveLast Method (And Pop/Push Methods Reimplemented)
    • Apply Method to All Elements in a List
    • Apply Closure to All Element in a Collection with collect
    • Transform Elements While Flattening
    • 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
    • Get Row Number In GINQ Result Set
    • 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
    • Revisited Getting the Sum of Items in a Collection
    • Sum the Values in a Object Array
    • Calculate Average For Collection
    • 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 List
    • Intersect Collections With Custom Comparator
    • Java 8 Stream Enhancements
    • Unmodifiable Collections
    • Shuffle List or Array
  • 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
    • Identity Closure
    • Add Some Curry for Taste
    • New Ways to Curry
    • Lambda Default Parameter Value
    • 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
    • Use Expanded Variables in SQL GString Query
  • 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
    • Make Sure Closeable Objects Are Closed Using withCloseable Method
  • 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
    • Preorder And Postorder Tree Traversal
    • 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
    • Creating Root JSON Array With JsonBuilder
    • Streaming JSON with StreamingJsonBuilder
    • Customizing JSON Output
    • Create YAML With YamlBuilder
    • Parse YAML With YamlSlurper
  • 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
    • Add Map Constructor With Annotation
    • 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
    • Creating Extra Method Supporting Named Arguments Using @NamedVariant Annotation
    • 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
    • Implement Interface And Abstract Methods Automatically
  • Metaprogramming
    • Create a Singleton Class
    • 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
    • Customize Log Variable Name with Log AST Annotations
    • 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
    • Redirecting Print Methods In Scripts
    • 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
    • Download Grab Dependencies In IntelliJ IDEA
  • Miscellaneous
    • Inspect Method Returns Nicely Formatted Object Values
    • Interrupted Sleeping
    • Using Tuples
    • Tuples With Up To 9 Items
    • Using Tuples
    • Where Is My Class?
    • 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
    • Reading TOML Configuration
    • Creating TOML Configuration With TomlBuilder
    • Using Macros For Getting String Representation Of Variables
    • Using Macros For Getting More Information About Variables
    • 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 60 Day 100% Happiness Guarantee

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

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

80% Royalties. Earn $16 on a $20 book.

We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earnedover $13 millionwriting, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. 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) and EPUB (for phones, tablets and Kindle). 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

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

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. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub