Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List minus(Object removeMe) method



Description

Groovy List minus(Object removeMe) method creates a new List composed of the elements of the original without passed object.

Syntax

List minus(Object removeMe)

Parameters

removeMe − The value to minus from the list.

Return Value

New list of values minus the object passed.

Example - Getting sublist of integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14]; 
def newlst = [];

newlst = lst.minus(12); 
println(newlst); 

newlst = lst - 12; 
println(newlst); 

Output

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

[11, 13, 14]
[11, 13, 14]

Example - Getting sublist of strings

Following is an example of the usage of this method −

main.groovy

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

newlst = lst.minus("Orange"); 
println(newlst); 

newlst = lst - "Orange"; 
println(newlst); 

Output

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

[Apple, Peach, Mango]
[Apple, Peach, Mango]

Example - Getting sublist 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.minus(new Student(2, "Robert")); 
println(newlst); 

newlst = lst - new Student(2, "Robert"); 
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 ], [ 3, Adam ]]
[[ 1, Julie ], [ 3, Adam ]]
groovy_lists.htm
Advertisements