Groovy Tip "in" keyword

Source: Internet
Author: User

Speaking of the "in" keyword is rarely used in the Java language because it is introduced later, i.e. the JDK5 enhanced for loop. The groovy language also retains this functionality so that we can write code similar to the following:

def list = [1,2,3]

      for(i in list)
      {
         println i
      }

The results of the operation are:

1
2
3

This enhanced for loop can also be used on loops on the map, such as:

def map = [a:"1",b:"2"]

      for(i in map)
      {
         println "${i.key} : ${i.value}"
      }

The results of the operation are:

a : 1
b : 2

In addition, the "in" keyword is also introduced into the groovy language to determine whether an object is an element of a collection class. Such as:

def list = [1,2,3]

      println 1 in list

      println 5 in list

The results of the operation are:

true
false

Others, such as set objects, can also be used in this way:

def set = [1,2,3,4,3,4] as Set

      println 1 in set

      println 5 in set

The results of the operation are:

true
false

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.