Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List split(Closure condition) method



Description

Groovy List split(Closure condition) method splits the list into two collection based on the condition specified by the Closure. First list contains the matched items whereas second list contains the unmatched items.

Syntax

public List split(Closure condition)

Parameters

condition − a closure whose evaluation decides the item(s) to be matched

Return Value

A list of two collections where first one contains matched items and second contains the unmatched one.

Example - Spliting elements of a List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14, 15, 16, 17]

// split even odd numbers
splitedList = lst.split{ it %2 == 0}

// print splited lists
println(splitedList[0])
println(splitedList[1])

Output

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

[12, 14, 16]
[11, 13, 15, 17]

Example - Spliting elements of a List of Strings

Following is an example of the usage of this method −

main.groovy

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

// split list based on size
splitedList[1] = lst.split{ it.size() == 5}

// print splited lists
println(splitedList[0])
println(splitedList[1])

Output

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

[Apple, Mango]
[Orange, Papaya]

Example - Spliting 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")]

// spliting objects based on even/odd roll numbers
splitedList = lst.split{ it.getRollNo() % 2 == 0}

// print splited lists
println(splitedList[0])
println(splitedList[1])

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 −

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