Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Range subList() method



subList() method returns a view of the portion of this Range between the specified fromIndex, inclusive, and toIndex, exclusive

Syntax

List subList(int fromIndex, int toIndex)

Parameters

  • fromIndex − Starting index of the range.

  • toIndex − End Index of the range.

Return Value

Returns the list of range values from specified starting to ending index.

Example - Getting a sublist from a range of numbers

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

Example.groovy

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

Output

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

[2, 3, 4]
[5, 6, 7, 8]

Example - Getting sublist from a range of characters

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

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of characters
      def array = 'a'..'z'; 
      println(array.subList(1,4));
      println(array.subList(4,8));	
   } 
}

Output

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

[b, c, d]
[e, f, g, h]

Example - Getting sublist from a range of special characters

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

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of special characters
      def array = '&'..'!'; 
      println(array.subList(1, 2));
   } 
}

Output

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

[%]
groovy_ranges.htm
Advertisements