Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List addAll(int index, Object[] items) method



Description

Groovy List add(int index, Object[] items) method adds the all the items at the provided index of the List.

Syntax

boolean add(int index, Object[] items)

Parameters

  • items − array of items to be added to the list.

  • index − the index where the array needs to be added.

Return Value

A Boolean value on whether the value was added.

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];

println(lst);
lst.add(2,[20, 21, 22]);

println(lst);

Output

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

[11, 12, 13, 14]
[11, 12, [20, 21, 22], 13, 14]

Example - Adding Elements to List of Strings

Following is an example of the usage of this method −

main.groovy

def lst = ["Apple","Orange","Mango"];
		
println(lst);
lst.add(2, ["Peach", "Papaya"]);
println(lst);

Output

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

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

Example - Adding Elements to List of Objects

Following is an example of the usage of this method −

main.groovy

def lst = [];
		
lst.add(new Student(1, "Julie"));
lst.add(new Student(2, "Robert"));
lst.add(0, [new Student(3, "Adam"), new Student(4, "Mark")]);
println(lst)


class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

Output

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

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