Tuesday 5 October 2021

Exercise Using Closure in Groovy Scripting groovy traing telugu 29

 Watch This Video


[Exercise] Using Closures
Closure Basics

Locate the class groovy.lang.Closure and spend a few minutes looking through documentation.

Create a Method that accepts a closure as an argument

Create a closure that performs some action

Call the method and pass the closure to it.

Create a list and use them each to iterate over each item in the list and print it out

Hint - You can use the implicit it or use your own variable

Create a map of data and iterate over it using each method. 

This method can take a closure that accepts 1 or 2 arguments. 

Use 2 arguments and print out the key and value on each line.

Demonstrate the use of curry and try to come up with an example different from the one we used in the lecture. 

Explore the GDK

In the following exercises we are going to explore the GDK to find some methods that take closures and learn how to use them. Hint - I would narrow your search to java.util.Collection, java.lang.Iterable & java.util.List

Search for the find and findAll methods.

What is the difference between the two? 

Write some code to show how they both work.

Search for the any and every methods.

What is the difference between the two? 

Write some code to show how they both work. 

Search for the method groupBy that accepts a closure

What does this method do? 

Write an example of how to use this method.

def mymethod(Closure c){
def foo={
List names=["Dan","Vega","Jhon","rashmi","rasi"]
names.each{name ->
 println name
Map teams=[baseball:"Cleveland Indians", basketball:"Cleveland Cavs", football:"Cleveland Browns"]
teams.each{k,v ->
def greet ={ String greeting, String name ->
println "$greeting,$name"

greet ("HELLO","DAN")
def sayHello=greet.curry("HELLO")

List people=[
[name:"Jame", city:"New York City"]
[name:"Jhon", city:"Cleveland"]
[name:"Mary", city:"New York City"]
[name:"Dan", city:"Cleveland"]
[name:"Ton", city:"New York City"]
[name:"Frank", city:"New York City"]
[name:"Jason", city:"Cleveland"]
println people.find{person ->"Cleveland"}
println people.findAll{person ->"Cleveland"}
println people.any{person ->"Cleveland"}
println people.every{person ->"Cleveland"}

def peopleByCity =people.groupBy{person ->}
println peopleByCity

No comments:

Post a Comment

Note: only a member of this blog may post a comment.