In a dynamic language such as groovy, closures are one of the key weapons. And the developers of these languages are naturally not going to give up using these weapons, and we can see that the closures are widely used in the groovy language collection classes. Among them, each method is such a method of using closures.
We know that in Java, we use the following statement to traverse the collection class object:
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i))
}
In the groovy language, we use each method to traverse the collection class object:
list.each{
it ->
println it
}
is much simpler than a traditional for loop statement, but it can still be simpler:
list.each{
println it
}
This is because, by default, the input parameters for each method are it.
If we want to get the position of an element in the collection class object through each method, we should use this:
list.eachWithIndex{
i,it ->
println"port: $i value: $it"
}
Below, we define a list object:
def list = [1,5,6,2,6,7]
Now, I want to determine if the above collection object is greater than 5 elements:
def have = false
list.each{
if(it>5)
{
have = true
break;
}
}
println have
The result found that the break language was not compiled. What to do?
def have = false
for(it in list){
if(it>5)
{
have = true
break;
}
}
println have
Yes, sometimes these old grammars are useful.