Groovy Tip 2:each method and break

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.