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 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
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
- 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
Authors have earned$10,071,608writing, 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
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. 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++ Best Practices
Jason TurnerLevel up your C++, get the tools working for you, eliminate common problems, and move on to more exciting things!
Digital-First Events
Joep Piscaer and Jana BorutaThe only resource you will ever need to launch your digital events program.
node-opcua by example
Etienne RossignonGet the best out of node-opcua through a set of documented examples by the author himself that will allow you to create stunning OPCUA Servers or Clients.
Cloud Strategy
Gregor Hohpe“Strategy is the difference between making a wish and making it come true.” A successful migration to the cloud can transform your organization, but it shouldn’t be driven by wishes. This book tells you how to develop a sound strategy guided by frameworks and decision models without being overly abstract nor getting lost in product details.
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.
C++20
Rainer GrimmC++20 is the next big C++ standard after C++11. As C++11 did it, C++20 changes the way we program modern C++. This change is, in particular, due to the big four of C++20: ranges, coroutines, concepts, and modules.
The book is almost daily updated. These incremental updates ease my interaction with the proofreaders.
Sockets and Pipes
Type ClassesSockets and Pipes is not an introduction to Haskell; it is an introduction to writing software in Haskell. Using a handful of everyday Haskell libraries, this book walks through reading the HTTP specification and implementing it to create a web server.
Atomic Kotlin
Bruce Eckel and Svetlana IsakovaFor both beginning and experienced programmers! From the author of the multi-award-winning Thinking in C++ and Thinking in Java together with a member of the Kotlin language team comes a book that breaks the concepts into small, easy-to-digest "atoms," along with exercises supported by hints and solutions directly inside IntelliJ IDEA!
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.
Introducing EventStorming
Alberto BrandoliniThe deepest tutorial and explanation about EventStorming, straight from the inventor.
Top Bundles
- #1
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... - #2
Django for Beginners/APIs/Professionals
3 Books
- #3
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... - #4
Cisco CCNA 200-301 Complet
4 Books
Ce lot comprend les quatre volumes du guide préparation à l'examen de certification Cisco CCNA 200-301. - #5
Modern Management Made Easy
3 Books
Read all three Modern Management Made Easy books. Learn to manage yourself, lead and serve others, and lead the organization. - #6
Linux Administration Complet
4 Books
Ce lot comprend les quatre volumes du Guide Linux Administration :Linux Administration, Volume 1, Administration fondamentale : Guide pratique de préparation aux examens de certification LPIC 1, Linux Essentials, RHCSA et LFCS. Administration fondamentale. Introduction à Linux. Le Shell. Traitement du texte. Arborescence de fichiers. Sécurité... - #7
CCDE Practical Studies (All labs)
3 Books
CCDE lab - #8
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... - #9
Cloud Architect: Transform Technology and Organization
2 Books
Architects don't just recite product names and features. They understand the options, decisions, and trade-offs behind them. They earn credibility and maintain authenticity by connecting the penthouse with the engine room. Get two essential books that redefine the role of the software and IT architect at one low price:37 Things One Architect... - #10
Mastering Containers
2 Books
Docker and Kubernetes are taking the world by storm! These books will get you up-to-speed fast! Docker Deep Dive is over 400 pages long, and covers all objectives on the Docker Certified Associate exam.The Kubernetes Book includes everything you need to get up and running with Kubernetes!