Leanpub Header

Skip to main content

Groovy Goodness Notebook

Experience the Groovy programming language through code snippets

Learn more about (hidden) Groovy features with code snippets and short articles. The articles and code will get you started quickly and will give more insight in Groovy.

The author is letting you choose the price you pay for this book!

Pick Your Price...
PDF
EPUB
WEB
397
Pages
About

About

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

Share this book

Categories

Price

Pick Your Price...

Minimum price

$14.99

$14.99

You pay

$14.99

Author earns

$11.99
$

All prices are in US $. You can pay in US $ or in your local currency when you check out.

EU customers: prices exclude VAT, which is added during checkout.

...Or Buy With Credits!

Number of credits (Minimum 1)

1
The author will earn $12.00 from your purchase!
You can get credits monthly with a Reader Membership

Author

About the Author

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.

Contents

Table of Contents

About Me

Introduction

  1. Code samples

Syntax

  1. Default Imports
  2. Semicolons are Optional
  3. Optional return Keyword
  4. Automatic Return Value Casting
  5. Static Imports
  6. Optional Parenthesis
  7. Check for Object Equality
  8. Using def to Define a Variable
  9. Using Lists and Maps As Constructors
  10. Parameters with Default Values
  11. Named Parameters are Converted to Map
  12. Use a Map as Interface Implementation
  13. MultiMethods or Multiple Dispatch
  14. Multiple Overloaded Operator Methods for Nice API
  15. Operator Overloading in Reverse
  16. Exception Handling
  17. The With Method
  18. Easy Object Creation With Tap Method
  19. The Switch Statement
  20. Use Map in Switch Statement
  21. Using The Switch Expression
  22. Tell the Groovy Truth
  23. We Can Handle the Truth
  24. Groovy Truth for Simple Type Arrays
  25. Boolean Implications
  26. The as Keyword
  27. Define Your Own Type Conversion
  28. Using Project Coin Features Also With Older Java Versions
  29. Getting and Setting Properties
  30. GroovyBeans the Simpler JavaBeans
  31. Powerful Assert
  32. Multiple Assignments
  33. Multiple Assignments Revisited
  34. Turn Methods into Closures
  35. Use Keywords as Method Names
  36. Chaining Traits
  37. Implementing Traits at Runtime
  38. Using Implicit call() Method
  39. Groovy Mystic Expressions
  40. Invoke Methods Dynamically
  41. Create Class Instance Dynamically
  42. Know More About a Class
  43. Getting Information About Objects
  44. Get Hints About Missing Methods or Properties
  45. Executing String or List
  46. Run Code at a Specified Time
  47. Using AntBuilder
  48. Add a ShutdownHook
  49. Add a ShutdownHook
  50. Defining Public Accessible Constant Fields
  51. Direct Field Access In (Super) Classes
  52. Use Optional In Conditional Context
  53. Check Item Is Not In A Collection With !in

Operators

  1. Safe Navigation to Avoid NullPointerException
  2. The Elvis Operator ?:
  3. The Elvis Assignment Operator
  4. The Spaceship Operator
  5. The Spread-Dot Operator
  6. The Spread Operator
  7. Are You In? (Membership Operator)
  8. Is Object in Class Hierarchy
  9. Check Object Instances Are The Same With === Operator
  10. Using !instanceof Operator
  11. Safe Index Based Access For Lists, Arrays and Maps
  12. Using The Call Operator ()

Numbers

  1. BigDecimal
  2. Round and Truncate Decimal Values
  3. Truncate And Round BigDecimal Values
  4. Integer Divisions
  5. Make a Number Absolute
  6. Raising the Power of Numbers

Strings

  1. Turn Methods into Closures
  2. New Dollar Slashy Strings
  3. Get to Know More About a GString
  4. Check if String is a Number
  5. What Character Are You?
  6. Access Strings with Subscript Operator
  7. Capitalize Strings
  8. Uncapitalize Strings
  9. Base64 Encoding
  10. Check if a String Only Contains Whitespaces
  11. Convert String to Boolean
  12. Padding Strings
  13. Working with Lines in Strings
  14. Getting Parts Of A String Enclosed By Strings
  15. Using the replaceAll Methods from String
  16. Replace Characters in a String with CollectReplacements
  17. Text Translation
  18. Remove Parts of a String
  19. Remove Part of String With Regular Expression Pattern
  20. Taking Or Dropping Number Of Characters From A String
  21. Splitting Strings
  22. Get Unique Characters in a String
  23. Partial Matches
  24. Transform String into Enum
  25. String Continuation
  26. Strip Leading Spaces from Lines
  27. Strip Leading Spaces from Lines with Margin
  28. Formatted Strings with sprintf
  29. Expand or Unexpand Space or Tab Delimited Text
  30. Normalize and Denormalize Linefeeds and Carriage Returns
  31. Base64 URL and Filename Safe Encoding
  32. Calculate MD5 And SHA Hash Values
  33. Converting Byte Array to Hex String
  34. GString as Writable
  35. Closure as Writable

Regular Expressions

  1. Using Regular Expression Pattern Class
  2. Matchers for Regular Expressions

Dates

  1. Working with Dates
  2. Setting Date and Calendar Values with Subscript Operators
  3. Convert Date to java.sql.Timestamp
  4. Convert Date to Calendar
  5. Format Dates with TimeZone
  6. Parse Date.toString() Value
  7. Use the set Method to Define a Date or Calendar Value
  8. Create New Date from Old Date with Updates
  9. Create New Date or Calendar from Existing and Set Property Value
  10. Clear Time Portion of a Date
  11. Date and Time Durations and the TimeCategory
  12. Loop Through Date and Calendar Ranges
  13. Using Subscript Operator With Multiple Fields On Date Related Objects

List, Ranges and Arrays

  1. Create Elements in Collection Definition
  2. Finding Data in Collections
  3. Find First Non-Null Result From a Closure
  4. Find Non-Null Results After Transformation in a Collection
  5. Find Elements Matching Groovy Truth
  6. Removing Elements From a Collection
  7. Use Ranges as Subscript Operators
  8. Use Strings as Subscript Operator
  9. Using the Subscript Operator on Iterators
  10. Use Range By Method To Set Steps Between Numbers
  11. Closed And Open Ranges
  12. Using String Values In Ranges
  13. Looping in Different Ways
  14. Keep Your Values in Ranges
  15. Getting the Tail of a List
  16. Getting Head And Tail From an Array of Objects
  17. Getting All Init And Tail Values Recursively
  18. Getting the First and Last Element of an Iterable
  19. Getting All But the Last Element in a Collection with Init Method
  20. Take and Drop Items from a List
  21. Drop or Take Elements with Condition
  22. Take Or Drop Last Items From a Collection
  23. Getting the Indices of a Collection
  24. Combine Elements Iterable with Index
  25. Pop And Push Items In a List
  26. Remove Last Item From List Using RemoveLast Method (And Pop/Push Methods Reimplemented)
  27. Apply Method to All Elements in a List
  28. Apply Closure to All Element in a Collection with collect
  29. Transform Elements While Flattening
  30. Use Collect with Initial Collection Value
  31. Transform Collection to a Map with collectEntries
  32. Transform Items into a Collection with collectMany
  33. Collect on Nested Collections
  34. Recursively Collect Elements
  35. Join Elements to a String
  36. Using the Inject Method
  37. Using the GroupBy Method
  38. GroupBy with Multiple Closures
  39. Removing Duplicate Elements in a Collection
  40. Sort or Remove Duplicates without Changing the Original Collection
  41. New Methods to Sort and Remove Duplicates From Collection
  42. Using the OrderBy Comparator
  43. Get Row Number In GINQ Result Set
  44. GroovyCollections Utility Class
  45. Splitting with Closures
  46. Intersect Collections
  47. Collate a List into Sub-lists
  48. Getting All Subsequences of a List
  49. Looping Through Each Permutation in a Collection
  50. Counting the Items in a List
  51. Count Occurrences in a Collection or Map
  52. Getting the Sum of Items in a Collection
  53. Revisited Getting the Sum of Items in a Collection
  54. Sum the Values in a Object Array
  55. Calculate Average For Collection
  56. Represent a List as String
  57. Create a List with Default Values
  58. Add Items to a List at Specified Position
  59. Working with Arrays
  60. See if List and Object Array are Equal
  61. Convert Collection to Set with Only Unique Elements
  62. See if Sets are Equal
  63. Immutable Collections
  64. Observable Map and List
  65. Enhancements for Iterable Implementations
  66. Swapping Elements in a List
  67. Intersect Collections With Custom Comparator
  68. Java 8 Stream Enhancements
  69. Unmodifiable Collections
  70. Shuffle List or Array

Maps

  1. Check if Maps are Equal
  2. Sorting a Map
  3. Turn a List into a Map
  4. Complex Keys in Maps
  5. Use inject Method on a Map
  6. Intersect Maps
  7. Subtracting Map Entries
  8. Process Map Entries in Reverse
  9. Getting a Submap from a Map
  10. Grouping Map Elements
  11. Get Value from Map or a Default Value
  12. Map with Default Values
  13. Determine Min and Max Entries in a Map
  14. Represent Map As String
  15. Turn A Map Or List As String To Map Or List

Closures

  1. Passing Closures to Methods
  2. Closure Arguments
  3. Identity Closure
  4. Add Some Curry for Taste
  5. New Ways to Curry
  6. Lambda Default Parameter Value
  7. Implicit Closure Coercion
  8. Return Closure From Another Closure or Method
  9. Chain Closures Together with Closure Composition
  10. Recursion with Closure Trampoline Capability
  11. Cache Closure Results with Memoization
  12. Info About Closure Parameters
  13. Setting a Closure's Delegate
  14. Invoke Anonymous Closure
  15. Implicit Method doCall in Closure
  16. Closure as a Class
  17. Use Closures as Java Lambda Expressions
  18. Use Constructor as Method Pointer

SQL

  1. Groovy SQL
  2. Groovy SQL DataSet
  3. Using Named (Ordinal) Parameters with Groovy SQL
  4. Access ResultSetMetaData with Groovy SQL
  5. Paging Support in Groovy SQL
  6. Use Expanded Variables in SQL GString Query

Files, Readers, Writers and URLs

  1. Working with Files
  2. Working on Files or Directories (or Both) with FileType
  3. Finding Files with FileNameFinder
  4. Delete Non-empty Directory Recursively with File
  5. Traversing a Directory
  6. Creating Files And Directories With Nice DSL Using FileTreeBuilder
  7. Calculating Directory Size
  8. Extra Methods for NIO Path
  9. WithReader and withWriter
  10. Transforming Reader Input to Writer Output
  11. Append Values to Appendable Objects
  12. Apply Read and Write Locking
  13. Reading URL Content
  14. Use Connection Parameters to Get Text From URL
  15. Make Sure Closeable Objects Are Closed Using withCloseable Method

XML and JSON

  1. Pretty Print XML
  2. Creating XML with MarkupBuilder
  3. Refactor XML Creation with StreamingMarkupBuilder
  4. Reading XML
  5. Type Conversion Using GPathResult When Reading XML
  6. Change XML Structure
  7. Preorder And Postorder Tree Traversal
  8. Getting Groovy with DOM
  9. Nested Templates with MarkupTemplateEngine
  10. Use Custom Template Class with MarkupTemplateEngine
  11. Using Layouts with MarkupTemplateEngine
  12. Parse JSON with JsonSlurper
  13. Relax... Groovy Will Parse Your Wicked JSON
  14. Build JSON with JsonBuilder and Pretty Print JSON Text
  15. Creating Root JSON Array With JsonBuilder
  16. Streaming JSON with StreamingJsonBuilder
  17. Customizing JSON Output
  18. Create YAML With YamlBuilder
  19. Parse YAML With YamlSlurper

AST transformations

  1. Newify to Create New Instances
  2. Create a Singleton Class
  3. Inject Logging Using Annotations
  4. Customise Log AST Annotations
  5. Easy toString Creation for Our Classes
  6. Customize ToString Creation
  7. Tuple Constructor Creation
  8. Add Map Constructor With Annotation
  9. Generate equals and hashcode Methods with EqualsAndHashCode Annotation
  10. Inherit Constructors From Parent Classes
  11. Canonical Annotation to Create Mutable Class
  12. Make Class Cloneable With @AutoClone
  13. Combining Annotations with AnnotationCollector
  14. Change Scope Script Variable with Field Annotation
  15. Add Java-style Listener Support with ListenerList Annotation
  16. Lazy Initialization of Properties
  17. Making a Class Immutable
  18. Create CopyWith Method with Immutable Annotation
  19. Synchronized Annotation for Synchronizing Methods
  20. Create Indexed Property Getter and Setter Methods
  21. Bound and Constrained Properties in GroovyBeans
  22. Delegate to Simplify Code
  23. Choose Which Delegated Methods to Use
  24. Creating Extra Method Supporting Named Arguments Using @NamedVariant Annotation
  25. Cache Methods Invocations with Memoize Annotation
  26. Using Package Scoped Methods, Fields and Classes
  27. Use Builder AST Transformation for Fluent API
  28. Using Builder to Create Fluent API for Other Classes
  29. @Builder Definition with Extra Type Checks
  30. More Efficient Tail Recursion With TailRecursive Annotation
  31. Use Sortable Annotation to Make Classes Comparable
  32. Implement Interface And Abstract Methods Automatically

Metaprogramming

  1. Create a Singleton Class
  2. Use a Category and Get a Return Value
  3. Mixin Functionality to Classes
  4. Apply Mixin to Object Instances
  5. Add Methods Dynamically to Classes with ExpandoMetaClass
  6. Create Dynamic Methods
  7. A Bit of metaClass DSL
  8. Adding or Overriding Methods with ExpandoMetaClass
  9. Override getProperty Method with Dynamic Groovy
  10. Implementing MetaClass Methods with Same Name but Different Arguments
  11. Add Static Methods with MetaClass to Classes
  12. Override and Use Old Implementation with Dynamic Methods
  13. Add Methods to Interfaces with ExpandoMetaClass
  14. Expando as Dynamic Bean
  15. Check If Method or Property is Available
  16. Intercept Methods with Interceptors
  17. Magic Package to Add Custom MetaClass
  18. Adding Extra Methods Using Extension Modules

DSL and Builder Support

  1. Building Object Graphs
  2. Create Simple Builders with Closures
  3. Solve Naming Conflicts with Builders
  4. Building a GUI with SwingBuilder
  5. Command Chain Expressions for Fluid DSLs
  6. Store Closures in Script Binding
  7. Add Imports Transparently to Scripts with ImportCustomizer
  8. Add AST Transformations Transparently to Scripts
  9. Create Our Own Script Class
  10. Set Script Class with BaseScript Annotation
  11. BaseScript with Abstract Run Script Method
  12. Set Delegating Class for Script
  13. Customize Log Variable Name with Log AST Annotations
  14. Define Compilation Customizers With Builder Syntax
  15. Restricting Script Syntax With SecureASTCustomizer

Scripts

  1. Using Groovy on the Command-Line
  2. Default Groovy Script File Extensions
  3. Variable Scope in Scripts
  4. Grab That Dependency
  5. See More Info About Downloading With Grape
  6. Configuring Grape to Use Classloader
  7. Use GrabResolver for Custom Repositories
  8. Resolve Module Location with Grape
  9. Change Directory For Saving Dependencies Grape
  10. Exclude Transitive Dependencies With Grape
  11. Running Groovy Scripts in Java with GroovyClassLoader
  12. Simple Evaluation of Groovy Expressions in Java
  13. Compiled Groovy Script is a Java Class
  14. ServerSocket Scripts
  15. Run Remote Scripts via URL
  16. Running Scripts from a JAR Archive
  17. Redirecting Print Methods In Scripts
  18. Customize Groovy Console Visual Output
  19. Using Groovy for Git Hooks

Testing

  1. Running a Unit Test
  2. Testing for Expected Exceptions
  3. Create Stubs for Testing

IDE

  1. IntelliJ IDEA Intentions For String Values
  2. Turn Map Into Class With IntelliJ IDEA
  3. Turn Method Parameters Into Named Map Arguments With IntelliJ IDEA
  4. IntelliJ IDEA Formatting Of Closure Chains
  5. Download Grab Dependencies In IntelliJ IDEA

Miscellaneous

  1. Inspect Method Returns Nicely Formatted Object Values
  2. Interrupted Sleeping
  3. Using Tuples
  4. Tuples With Up To 9 Items
  5. Using Tuples
  6. Where Is My Class?
  7. Parsing Commandline Arguments with CliBuilder
  8. Get Properties from ReleaseInfo
  9. Using ConfigSlurper with Configuration Scripts
  10. Extend ConfigSlurper with Custom Environments Sections
  11. Check Configuration Property Is Set In ConfigObject
  12. Reading TOML Configuration
  13. Creating TOML Configuration With TomlBuilder
  14. Using Macros For Getting String Representation Of Variables
  15. Using Macros For Getting More Information About Variables
  16. Using the Template Engines
  17. Groovlets as Lightweight Servlets
  18. Access XML-RPC API
  19. Customise Groovydoc Output With Gradle
  20. Customising The Groovy Compiler
  21. Using the ServletCategory
  22. Using GroovyMBeans for Easy JMX
  23. Share Data in Concurrent Environment with Dataflow Variables

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

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...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

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

In fact, authors have earned over $14 million writing, 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