Groovy Goodness Notebook
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 October 1, 2021 to include the following new subjects:
- Direct Field Access In (Super) Classes
- Identity Closure
- Groovy Goodness Notebook Is Updated
- Uncapitalize Strings
- Creating Root JSON Array With JsonBuilder
- Using The Call Operator ()
- Redirecting Print Methods In Scripts
- Download Grab Dependencies In IntelliJ IDEA
- Make Sure Closeable Objects Are Closed Using withCloseable Method
- Add Map Constructor With Annotation
- Base64 URL and Filename Safe Encoding
- Calculate MD5 And SHA Hash Values
- Creating Extra Method Supporting Named Arguments Using @NamedVariant Annotation
- Customizing JSON Output
- Easy Object Creation With Tap Method
- Getting All Init And Tail Values Recursively
- Implement Interface And Abstract Methods Automatically
- Intersect Collections With Custom Comparator
- Java 8 Stream Enhancements
- Preorder And Postorder Tree Traversal
- Remove Last Item From List Using RemoveLast Method (And Pop/Push Methods Reimplemented)
- Truncate And Round BigDecimal Values
- Tuples With Up To 9 Items
- Unmodifiable Collections
- Use Optional In Conditional Context
- Use Range By Method To Set Steps Between Numbers
- Using String Values In Ranges
- Where Is My Class?
- Use Expanded Variables in SQL GString Query
- Transform Elements While Flattening
- Calculate Average For Collection
- Check Item Is Not In A Collection With !in
- Create YAML With YamlBuilder
- The Elvis Assignment Operator
- Lambda Default Parameter Value
- Parse YAML With YamlSlurper
- Shuffle List or Array
- Check Object Instances Are The Same With === Operator
- Getting Parts Of A String Enclosed By Strings
- Safe Index Based Access For Lists, Arrays and Maps
- Taking Or Dropping Number Of Characters From A String
- Using !instanceof Operator
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
Bundles that include this book
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
- 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
-
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
- 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
- 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
- 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
- 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.
See full terms
Do Well. Do Good.
Authors have earned$11,595,069writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
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), EPUB (for phones and tablets) and MOBI (for 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
Top Books
C++20 - The Complete Guide
Nicolai M. JosuttisAll the new language and library features of C++20 (for those who know previous versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
SignalR on .NET 6 - the Complete Guide
Fiodar SazanavetsLearn everything there is to learn about SignalR and how to integrate it with the latest .NET 6 and C# 10 features. Learn how to connect any type of client to SignalR, including plain WebSocket client. Learn how to build interactive applications that can communicate with each other in real time without making excessive calls.
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
R Programming for Data Science
Roger D. PengThis book brings the fundamentals of R programming to you, using the same material developed as part of the industry-leading Johns Hopkins Data Science Specialization. The skills taught in this book will lay the foundation for you to begin your journey learning data science. Printed copies of this book are available through Lulu.
The easiest way to learn design patterns
Fiodar SazanavetsLearn design patterns in the easiest way possible. You will no longer have to brute-force your way through each one of them while trying to figure out how it works. The book provides a unique methodology that will make your understanding of design patterns stick. It can also be used as a reference book where you can find design patterns in seconds.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
CCIE Service Provider Version 4 Written and Lab Exam Comprehensive Guide
Nicholas RussoThe service provider landscape has changed rapidly over the past several years. Networking vendors are continuing to propose new standards, techniques, and procedures for overcoming new challenges while concurrently reducing costs and delivering new services. Cisco has recently updated the CCIE Service Provider track to reflect these changes; this book represents the author's personal journey in achieving that certification.
Cronache di Domain-Driven Design
Francesco Strazzullo, Matteo Baglini, Gianluca Padovani, Emanuele DelBono, Marco Consolaro, Alessandro Colla, Uberto Barbini, Alberto Acerbis, Julie Camosseto, DDD Open, and Alberto BrandoliniCronache di Domain-Driven Design: un libro corale in italiano fatto di storie indipendenti tra loro, che sono il risultato dell’applicazione di Domain-Driven Design su progetti reali.
Functional event-driven architecture: Powered by Scala 3
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way, mainly powered by Fs2 streams in Scala 3!
Leverage your functional programming skills by designing and writing stateless microservices that scale, powered by stateful message brokers.
Top Bundles
- #1
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #2
Software Architecture for Developers: Volumes 1 & 2 - Technical leadership and communication
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #3
All the Books of The Medical Futurist
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy, digital health investments and how technology giants such as Amazon... - #4
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #6
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also... - #7
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible...