
- Groovy Tutorial
- Groovy - Home
- Groovy - Overview
- Groovy - Environment
- Groovy - Basic Syntax
- Groovy - Data Types
- Groovy - Variables
- Groovy - Optionals
- Groovy - Numbers
- Groovy - Strings
- Groovy - Ranges
- Groovy - Lists
- Groovy - Maps
- Groovy - Dates & Times
Groovy Operators
- Groovy - Operators
- Groovy - Arithmetic Operators
- Groovy - Assignment Operators
- Groovy - Relational Operators
- Groovy - Logical Operators
- Groovy - Bitwise Operators
- Groovy - Spaceship Operator
- Groovy - in Operator
- Groovy - Elvis Operator
- Groovy - Safe Navigation Operator
- Groovy Operator Precedence & Associativity
Control Statements
- Groovy - Decision Making
- Groovy - If Else Statement
- Groovy - Switch Statement
- Groovy - Loops
- Groovy - For Loop
- Groovy - For-in Loop
- Groovy - While Loop
- Groovy - Do While Loop
- Groovy - Break Statement
- Groovy - Continue Statement
Groovy File Handling
- Groovy - File I/O
- Java - Create a File
- Java - Write to File
- Java - Append to File
- Java - Read Files
- Java - Delete Files
- Java - File Properties
- Java - File Existence and Type
- Java - File Size
- Java - File Permissions
- Java - Directories
- Java - Listing Directories
- Java - Filtering Files/Directories
- Java - Deleting Directories
- Java - Renaming Files/Directories
Groovy Error & Exceptions
- Groovy - Exception Handling
- Groovy - try-catch Block
- Groovy - try-with-resources
- Groovy - Multi-catch Block
- Groovy - Nested try Block
- Groovy - Finally Block
- Groovy - throw Exception
- Groovy - Exception Propagation
- Groovy - Built-in Exceptions
- Groovy - Custom Exception
Groovy Multithreading
- groovy - Multithreading
- groovy - Thread Life Cycle
- groovy - Creating a Thread
- groovy - Starting a Thread
- groovy - Joining Threads
- groovy - Naming Thread
- groovy - Thread Scheduler
- groovy - Thread Pools
- groovy - Main Thread
- groovy - Thread Priority
- groovy - Daemon Threads
- groovy - Shutdown Hook
Groovy Synchronization
- groovy - Synchronization
- groovy - Block Synchronization
- groovy - Static Synchronization
- groovy - Inter-thread Communication
- groovy - Thread Deadlock
- groovy - Interrupting a Thread
- groovy - Thread Control
- groovy - Reentrant Monitor
- Groovy - Methods
- Groovy - Methods
- Groovy - Optional parenthesis
- Groovy - Named Arguments
- Groovy - Closures as Arguments
- Groovy - Method Overloading
- Groovy - Method Scope and Visibility
- Groovy - isCase Method
- Groovy - Implicit Return
- Groovy - Variable Arguments
- Groovy - Regular Expressions
- Groovy - Regular Expressions
- Groovy - Defining Regular Expressions
- Groovy - Matcher Object
- Groovy - Regex Tasks
- Groovy - XML
- Groovy - XML
- Groovy - Parsing XML
- Groovy - Creating XML
- Groovy - Modifying XML
- Groovy - Querying XML
- Groovy - Simplified Notation
- Groovy - Closure based Querying
- Groovy - Closure based Creation
- Groovy - JSON
- Groovy - JSON
- Groovy - Parsing JSON
- Groovy - Creating JSON using JsonOutput
- Groovy - Creating JSON using JsonBuilder
- Groovy - Modifying JSON
- Groovy - Error Handling
- Groovy - Handling JSON Arrays
- Groovy - JSON Array Operations
- Groovy - JSON Objects
- Groovy - JSON Object Operations
- Groovy - Generics
- Groovy - Generics
- Groovy - Declaring Generic Types
- Groovy - Bound Type Parameters
- Groovy - Wild Cards
- Groovy - Miscellaneous
- Groovy - Object Oriented
- Groovy - Closures
- Groovy - Annotations
- Groovy - JMX
- Groovy - DSLS
- Groovy - Database
- Groovy - Builders
- Groovy - Command Line
- Groovy - Unit Testing
- Groovy - Template Engines
- Groovy - Meta Object Programming
- Groovy Useful Resources
- Groovy - Quick Guide
- Groovy - Useful Resources
- Groovy - Discussion
Groovy - Best Practices in Ranges
Ranges are very useful in Groovy based development. We can keep best practices in mind to use them effectively. In this chapter, we're discussing best practices while using the ranges.
Select the right type
Ranges can be of multiple types in terms of exclusivity.
-
Inclusive Range - A range defined using start..end can be used when we need to include both starting and ending values of the sequence. It is commonly used when we need to perform certain set of iterations.
-
Exclusive Range - A range defined using start..<end can be used when we need to exclude ending value of the sequence. It is commonly used when zero based collections are used.
-
Exclusive Beginning Range - A range defined using start<..end or start<..<end can be used when we need to exclude begining of the sequence. A exclusive beginning range functionality is avaliable from Groovy 4.0+ onwards.
Utilitize Range methods
There are many useful methods on ranges as shown below.
Sr.No. | Methods & Description |
---|---|
1 |
contains()
Checks if a range contains a specific value |
2 |
get()
Returns the element at the specified position in this Range. |
3 |
getFrom()
Get the lower value of this Range. |
4 |
getTo()
Get the upper value of this Range. |
5 |
isReverse()
Is this a reversed Range, iterating backwards |
6 |
size()
Returns the number of elements in this Range. |
7 |
subList()
Returns a view of the portion of this Range between the specified fromIndex, inclusive, and toIndex, exclusive |
8 |
toArray()
Returns an array of elements of this range. |
9 |
step(stepSize)
Returns a new List using the steps on the elements of the range with specified interval |
10 |
toList()
Returns a list of elements of this range. |
Use Ranges for Iteration
Following example shows various features of ranges useful in iterations.
Example.groovy
class Example { static void main(String[] args) { // Inclusive loop for (i in 1..5) { println i } // Exclusive loop to iterate a list def myList = [10, 20, 30, 40] for (i in 0..<myList.size()) { println "Element at index $i: ${myList[i]}" } // Using step to get even numbers for (i in (0..10).step(2)) { println i // Output: 0, 2, 4, 6, 8, 10 } // Using each for a range (1..3).each { number -> println "Number: $number" } } }
Output
When we run the above program, we will get the following result −
1 2 3 4 5 Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Element at index 3: 40 0 2 4 6 8 10 Number: 1 Number: 2 Number: 3
Implement next() and compareTo() methods for Custom Objects
In case of ranges for custom object, implement the Comparable interface and implement next() for progression. It helps groovy to define a correct order and generate proper range of custom objects. Visit Custom Ranges for more details.
Idiomatic Approach
It is always good to use range methods like each, collect, findall over tranditional loops like for, while to iterate the range. It helps in making code more readable and maintainable.
Use Ranges for Iteration
Following example shows various features of ranges useful in iterations.
Example.groovy
class Example { static void main(String[] args) { // define a range of numbers from 1 to 10 def numbers = 1..10 // get and print even numbers using step and each numbers.step(2).each { println it } // get a list of squares and print def squares = numbers.collect { it * it } println squares // Check for a specific number if (numbers.contains(5)) { println "The range contains 5" } // get a sublist def firstThree = numbers.toList()[0..<3] println firstThree } }
Output
When we run the above program, we will get the following result −
1 3 5 7 9 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] The range contains 5 [1, 2, 3]