Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map sort(Comparator comparator) method



Description

Groovy Map sort(Comparator comparator) method sorts the map elements using the comparator passed. Original map is not modified.

Syntax

public Map sort(Comparator comparator)

Parameters

comparator − A comparator used to compare Map entries

Return Value

A sorted Map.

Example - Sorting a Map of String and String

Following is an example of the usage of this method −

main.groovy

import org.codehaus.groovy.runtime.NumberAwareComparator

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

// sort the map
result = map.sort(new NumberAwareComparator())

// print updated map
print(result)

Output

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

[A:Apple, B:Banana, C:Carrot]

Example - Sorting a Map of Integer and Integer

Following is an example of the usage of this method −

main.groovy

import org.codehaus.groovy.runtime.NumberAwareComparator

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

// sort the map
result = map.sort(new NumberAwareComparator())

// print updated map
print(result)

Output

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

[1:11, 2:12, 3:13]

Example - Sorting a Map of Integer and Object

Following is an example of the usage of this method −

main.groovy

import org.codehaus.groovy.runtime.NumberAwareComparator

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

// sort the map based on keys
result = map.sort(new NumberAwareComparator())

// print updated map
print(result)

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 −

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