Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List transpose() method



Description

Groovy List transpose() method transposes the list where list is a collection of columns. Collection of columns is converted to collection of rows. First element of each row contains the first element of each collection. Successive rows follows the same order.

Syntax

public List transpose()

Parameters

NA

Return Value

A transposed List.

Example - transposing a List of Integers

Following is an example of the usage of this method −

main.groovy

def lst =  [[1, 2], [11, 12]]
def transposeList = lst.transpose()

println(transposeList)

lst =  [[1, 2], [11, 12],[101, 102]]
transposeList = lst.transpose()

println(transposeList)

Output

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

[[1, 11], [2, 12]]
[[1, 11, 101], [2, 12, 102]]

Example - transposing a List of Strings

Following is an example of the usage of this method −

main.groovy

def lst =  [["A", "B"], ["Apple", "Banana"]]
def transposeList = lst.transpose()

println(transposeList)

lst =  [["A", "B"], ["Apple", "Banana"],["Avacado", "Berry"]]
transposeList = lst.transpose()

println(transposeList)

Output

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

[[A, Apple], [B, Banana]]
[[A, Apple, Avacado], [B, Banana, Berry]]

Example - transposeing a List of Objects

Following is an example of the usage of this method −

main.groovy

def lst =  [[1, 2], [new Student(1, "Julie"), new Student(2, "Robert")]]
def transposeList = lst.transpose()

println(transposeList)

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 ]]]
groovy_lists.htm
Advertisements