Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List grep(Object filter) method



Description

Groovy List grep(Object filter) method checks and returns the elements which matches the given filter.

Syntax

public List grep(Object filter)

Parameters

filter − a Object filter.

Return Value

A list of matching values

Example - Getting List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14, 15, 16, 17, 18, 19, 'a', 'b', null]

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

Output

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

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

Example - Filtering a List of Strings

Following is an example of the usage of this method −

main.groovy

def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
println(list.grep( ~/a+/ )) 
print(list.grep( ~/../ ))

Output

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

[a, aa]
[aa, bc]

Example - Filtering a List 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")];

println(lst)
println(lst.grep{it.getRollNo() % 2 == 0})

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