Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Range step() method



step() method returns the list by stepping through the range using given steps.

Syntax

List step(int step)

Parameters

step − amount by which elements are to be step.

Return Value

Returns the list of elements of range values.

Example - Getting List of odd numbers from a range of numbers

Following is an example of the usage of step() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of numbers
      def array = 1..10;		
      println(array.step(2)); 
   } 
}

Output

When we run the above program, we will get the following result −

[1, 3, 5, 7, 9]

Example - Reversing array using negative step

Following is an example of the usage of step() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of numbers
      def array = 1..10;		
      println(array.step(-1)); 
   } 
}

Output

When we run the above program, we will get the following result −

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Example - Getting List of even numbers from a range of numbers

Following is an example of the usage of step() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of numbers
      def array = 1..10;		
      println(array.step(-2)); 
   } 
}

Output

When we run the above program, we will get the following result −

[10, 8, 6, 4, 2]
groovy_ranges.htm
Advertisements