Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map reverseEach(Closure closure) method



Description

Groovy Map reverseEach(Closure closure) method allows to iterate a Map in reverse order.

Syntax

public Map reverseEach(Closure closure)

Parameters

closure − a one or two args closure to be applied on entries.

Return Value

Current map.

Example - Iterating entries of a Map of String and String in Reverse Order

Following is an example of the usage of this method −

main.groovy

// define a map
def map = ["A" : "Apple", "B" : "Banana", "C": "Carrot"] 

// iterate entries of map using 1 arg constructor
// in reverse order
map.reverseEach{entry -> println(entry.value)}

// iterate entries of map using 2 args constructors
// in reverse order
map.reverseEach{key, value -> println(value)}

Output

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

Carrot
Banana
Apple
Carrot
Banana
Apple

Example - Iterating entries of a Map of Integer and Integer in Reverse Order

Following is an example of the usage of this method −

main.groovy

// define a map
def map = [1 : 11, 2 : 12, 3: 13] 

// iterate entries of map using 1 arg constructor
// in reverse order
map.reverseEach{entry -> println(entry.value)}

// iterate entries of map using 2 args constructors
// in reverse order
map.reverseEach{key, value -> println(value)}

Output

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

13
12
11
13
12
11

Example - Iterating entries of a Map of Integer and Object in Reverse Order

Following is an example of the usage of this method −

main.groovy

// define a map
def map = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert"), 3: new Student(3,"Adam")] 

// iterate entries of map using 1 arg constructor
// in reverse order
map.reverseEach{entry -> println(entry.value)}

// iterate entries of map using 2 args constructors
// in reverse order
map.reverseEach{key, value -> println(value)}

class Student{
   int rollNo
   String name

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

   @Override
   public boolean equals(Object obj) {
      Student s = (Student)obj
      return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name)
   }
   
   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]"
   }
}

Output

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

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