Array of strings in groovy

177,371

Solution 1

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

Solution 2

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()
Share:
177,371
Lucas
Author by

Lucas

Full stack software developer passionate about solving real world problems using my programming skills. Always learning new technologies, tools and ideas that help me to solve hard problems. Open to remote positions as software developer. Expertise: Java, JPA/Hibernate, JSF , Spring, SQL, MongoDB, NodeJs/Express.js Frontend: Angular, React, JavaScript, Typescript, html5, css

Updated on July 05, 2022

Comments

  • Lucas
    Lucas almost 2 years

    In ruby, there is a indiom to create a array of strings like this:

    names = %w( lucas Fred Mary )
    

    Is there something like that in groovy?

  • tim_yates
    tim_yates over 14 years
    or indeed ["lucas", "Fred", "Mary"] as String[]
  • Dónal
    Dónal over 14 years
    or (String[])['Lucas', 'Fred', 'Mary']
  • Snekse
    Snekse over 9 years
    But sometimes APIs require a String[], so providing both options in the answer would be nice.
  • Snekse
    Snekse over 9 years
    I think toArray() returns an Object[], not a String[].
  • The Unknown Dev
    The Unknown Dev over 8 years
    Nice. I was actually looking to make an array, convert to list and then check if it contains a string, but I can skip the middle part by just creating the list directly and calling contains(). That's Groovy!