Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List asReversed method



Description

Groovy List asReversed() method is a utility method to get a reversed version of the current list without reversing the original list.

Syntax

public List asReversed()

Parameters

NA

Return Value

A reversed List version of current List.

Example - Getting Reversed List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14] 

// get the reversed list
def reversedList = mutable.asReversed()

// print the lists
println(lst)
println(reversedList)

Output

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

[11, 12, 13, 14]
[14, 13, 12, 11]

Example - Getting Reversed List of Strings

Following is an example of the usage of this method −

main.groovy

def lst = ["Apple", "Peach", "Orange", "Mango"]

// get the reversed list
def reversedList = mutable.asReversed()

// print the lists
println(lst)
println(reversedList)

Output

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

[Apple, Peach, Orange, Mango]
[Mango, Orange, Peach, Apple]

Example - Getting Reversed List of Objects

Following is an example of the usage of this method −

main.groovy

def lst = [new Student(1, "Julie"),new Student(2, "Robert"),new Student(3, "Adam")];
		
// get the reversed list
def reversedList = mutable.asReversed()

// print the lists
println(lst)
println(reversedList)

class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

Output

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

[[ 1, Julie ], [ 2, Robert ], [ 3, Adam ]]
[[ 3, Adam ], [ 2, Robert ], [ 1, Julie ]]
groovy_lists.htm
Advertisements