Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List grep() method



Description

Groovy List grep() method checks and returns the elements which matches the IDENTITY closure (follows the groovy truth).

Syntax

public List grep()

Parameters

NA

Return Value

A list of truthy values

Example - Getting truthy values from a List of Integers and falsey values

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14, 15, 0, null, 18, 19]

println(lst)
println(lst.grep())

Output

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

[11, 12, 13, 14, 15, 0, null, 18, 19]
[11, 12, 13, 14, 15, 18, 19] 

Example - Getting truthy values from a List of Strings and falsey values

Following is an example of the usage of this method −

main.groovy

def lst = ["Apple",null, "Mango","Orange",false, "Papaya", 0]

println(lst)
println(lst.grep())

Output

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

[Apple, null, Mango, Orange, false, Papaya, 0]
[Apple, Mango, Orange, Papaya] 

Example - Getting truthy values from a List of Objects and falsey values

Following is an example of the usage of this method −

main.groovy

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

println(lst)
println(lst.grep())

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 −

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