Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List multiply(Number factor) method



Description

Groovy List multiply() method returns a new List composed of the elements of the original repeated the number of times the factor passed. In case of non-primitive elements, multiple references of same instance are added. In case, duplicate are not allowed like Set, items will not be repeated.

Syntax

public list multiply(Number factor)

Parameters

factor − the number of times, items are to be appended.

Return Value

the multiplied List.

Example - Getting multiplied List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [1, 2, 3]

println(lst.multiply(2))

Output

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

[1, 2, 3, 1, 2, 3]

Example - Getting multiplied List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = ["Apple","Mango"]

println(lst.multiply(2))

Output

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

[Apple, Mango, Apple, Mango]

Example - Getting Multiplied List of Objects

Following is an example of the usage of this method −

main.groovy

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

println(lst.multiply(2))

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, Julie ], [ 2, Robert ], [ 1, Julie ], [ 2, Robert ]]
groovy_lists.htm
Advertisements