Groovy - Ranges
A range is shorthand for specifying a sequence of values. A Range is denoted by the first and last values in the sequence, and Range can be inclusive or exclusive. An inclusive Range includes all the values from the first to the last, while an exclusive Range includes all values except the last. Here are some examples of Range literals −
- 1..10 - An example of an inclusive Range
- 1..<10 - An example of an exclusive Range
- 'a'..'x' Ranges can also consist of characters
- 10..1 Ranges can also be in descending order
- 'x'..'a' Ranges can also consist of characters and be in descending order.
Following are the various methods available for ranges.
| 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. |
Example - Print a range of numbers
Following is an example of a range of numbers.
Example.groovy
class Example {
static void main(String[] args) {
def array = 1..5;
for(int i in array) {
println(i);
}
}
}
Output
When we run the above program, we will get the following result −
1 2 3 4 5
Example - Getting an element of a range
Following is an example of getting an element from a range of numbers.
Example.groovy
class Example {
static void main(String[] args) {
def array = 1..5;
println(array.get(2));
}
}
Output
When we run the above program, we will get the following result −
3
Example - Checking element in a range
Following is an example of getting an element from a range of numbers.
Example.groovy
class Example {
static void main(String[] args) {
def array = 1..5;
println(array.contains(2));
}
}
Output
When we run the above program, we will get the following result −
true
Important Concepts on Ranges
Usage of Ranges in Switch Statement
Best Practices in using Ranges