Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List plus(Iterable right) method



Description

Groovy List plus(Iterable right) method creates a new List composed of the elements of the original together with those specified in the iterable.

Syntax

List plus(Iterable right)

Parameters

right − The iterable of values to add to the list.

Return Value

New list of values.

Example - Adding elements to List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14]; 
def newlst = []; 
      
newlst = lst.plus([15,16]); 
println(newlst);

newlst = lst + [17]; 
println(newlst); 

Output

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

[11, 12, 13, 14, 15, 16]
[11, 12, 13, 14, 17]

Example - Adding elements to List of Strings

Following is an example of the usage of this method −

main.groovy

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

newlst = lst.plus(["Banana","Papaya"]); 
println(newlst); 

newlst = lst + ["Grapes"]; 
println(newlst); 

Output

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

[Apple, Peach, Orange, Mango, Banana, Papaya]
[Apple, Peach, Orange, Mango, Grapes]

Example - Getting Superlist of Objects

Following is an example of the usage of this method −

main.groovy

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

newlst = lst.plus([new Student(4, "Mark")]); 
println(newlst); 

newlst = lst + [new Student(4, "Mark")]; 
println(newlst); 

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