Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map toSorted(Comparator comparator) method



Description

Groovy Map toSorted(Comparator comparator) method sorts the elements of given map using supplied comparator to determine the ordering.

Syntax

public Map toSorted(Comparator comparator)

Parameters

comparator − comparator to compare Map entries

Return Value

Sorted map.

Example - Getting Sorted 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 = ["A" : "Apple","P":"Peach","C": "Carrot","B" : "Banana"] 

// get the sorted map
def result = map.toSorted(new NumberAwareComparator())

// print map
print(result)

Output

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

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

Example - Getting Sorted Map of Integer and Integer

Following is an example of the usage of this method −

main.groovy

import java.util.Comparator

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

// get the sorted map
def result = map.toSorted(new ValueComparator())

// print map
print(result)

class ValueComparator implements Comparator {
    public int compare(Object obj1, Object obj2){
        return obj1.value <=> obj2.value
    }
}

Output

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

[1:11, 2:12, 3:13, 4:14, 5:15]

Example - Getting Sorted Map of Integer and Integer

Following is an example of the usage of this method −

main.groovy

import java.util.Comparator

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

// get the sorted map
def result = map.toSorted(new RollNoComparator())

// print map
print(result)

class RollNoComparator implements Comparator {
    public int compare(Object obj1, Object obj2){
        return ((Student)obj1.getValue()).getRollNo() <=> ((Student)obj2.getValue()).getRollNo()
    }
}

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:[ 3, Adam ], 1:[ 1, Julie ], 2:[ 2, Robert ]]
groovy_maps.htm
Advertisements