Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List sort() method



Description

Groovy List size() method returns a sorted copy of the original List.

Syntax

List sort()

Parameters

NA

Return Value

The sorted list.

Example - Sorting a List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 3, 14]; 

def sortedList = lst.sort(); 
println(sortedList);  

Output

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

[3, 11, 12, 14]

Example - Sorting a List of Strings

Following is an example of the usage of this method −

main.groovy

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

def sortedList = lst.sort(); 
println(sortedList);  

Output

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

[Apple, Mango, Orange, Peach]

Example - Sorting a List of Objects

Following is an example of the usage of this method −

main.groovy

def lst = [new Student(1, "Julie"),new Student(3, "Robert"),new Student(2, "Adam")];

def sortedList = lst.sort(); 
println(sortedList);    

class Student implements Comparable {
   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 + " ]";
   }
   
   public int compareTo(Object obj){
      Student s = (Student)obj;
      return this.rollNo - s.rollNo   
   }
}

Output

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

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