Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List contains() method



Description

Groovy List contains() method returns true if this List contains the specified value.

Syntax

boolean contains(Object value)

Parameters

Value − The value to find in the list.

Return Value

True or false depending on if the value is present in the list.

Example - Checking Element in List of Integers

Following is an example of the usage of this method −

main.groovy

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

println(lst.contains(12)); 
println(lst.contains(18));

Output

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

true 
false

Example - Checking Element in List of Strings

Following is an example of the usage of this method −

main.groovy

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

println(lst.contains("Apple")); 
println(lst.contains("Peach"));

Output

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

true 
false

Example - Checking Element in 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(new Student(3, "Adam")); 

println(lst.contains(new Student(2, "Robert")))
println(lst.contains(new Student(4, "Jane")))

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);
   }
}

Output

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

true 
false
groovy_lists.htm
Advertisements