Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List takeWhile(Closure condition) method



Description

Groovy List takeWhile(Closure condition) method returns the longest prefix of the list where each element of the prefix is passing the condition mentioned in Closure.

Syntax

public List takeWhile(Closure condition)

Parameters

condition − A closure to be evaluated to true to continue taking elements.

Return Value

A prefix list of matching items where each element is evaluated to true as per given closure.

Example - Taking elements from List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 10, 15, 11]

// getting elements which are less than 13 
prefixItems = lst.takeWhile{it < 13}
println(prefixItems)

Output

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

[11, 12]

Example - Taking strings from a List of Strings

Following is an example of the usage of this method −

main.groovy

def lst = ["Apple","Mango","Orange","Papaya","Peach"]

// getting strings whose size is less than 6
prefixItems = lst.takeWhile{it.size() < 6}
println(prefixItems)

Output

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

[Apple, Mango]

Example - Taking few objects from 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")]

// getting objects where roll no is less than 3
lastTwoItems = lst.takeWhile{ it.getRollNo() < 3}
println(lastTwoItems)

// original list is intact
println(lst)

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