Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List leftShift() method



Description

Groovy List leftShift() method overloads the left shift operator to append the new value to the end of the current List easily.

Syntax

boolean leftShift(Object value)

Parameters

value − Value to be appended to the list.

Return Value

Return Value − A Boolean value on whether the value was added.

Example - Adding Element 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.leftShift(15);
println(lst);

lst << 16;
println(lst);

Output

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

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

Example - Adding Element to List of Strings

Following is an example of the usage of this method −

main.groovy

def lst = [];
		
println(lst);

lst.leftShift("Welcome");
println(lst);

lst << "To Tutorialspoint";
println(lst);

Output

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

[]
[Welcome]
[Welcome, To Tutorialspoint]

Example - Adding Element to List of Objects

Following is an example of the usage of this method −

main.groovy

def lst = [];
		
lst.leftShift(new Student(1, "Julie"));
lst << new Student(2, "Robert");
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 −

[[ 1, Julie ], [ 2, Robert ]]
groovy_lists.htm
Advertisements