Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List plus(int index, List additions) method



Description

Groovy List plus(int index, List additions) method creates a new List composed of the elements of the original together with those specified in the list inserted at specified index.

Syntax

public List plus(int index, List additions)

Parameters

  • index − index at which the first element from the additions iterable.

  • additions − The list of values to add to the list.

Return Value

New list of values.

Example - Adding elements to List of Integers at given index

Following is an example of the usage of this method −

main.groovy

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

Output

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

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

Example - Adding elements to List of Strings at given index

Following is an example of the usage of this method −

main.groovy

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

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

Output

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

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

Example - Adding elements to List of Objects at given index

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