Search code examples
arraysstringgroovy

Convert Array to string in Java/Groovy


I have a list like this:

List tripIds = new ArrayList()

def sql = Sql.newInstance("jdbc:mysql://localhost:3306/steer", "root", "", "com.mysql.jdbc.Driver")
        
sql.eachRow("SELECT trip.id from trip JOIN department WHERE organization_id = trip.client_id AND department.id = 1") {
  println "Gromit likes ${it.id}"
  tripIds << it.id
} 

On printing tripids gives me value:

  [1,2,3,4,5,6,]

I want to convert this list to simple string like:

 1,2,3,4,5,6

How can I do this?


Solution

  • Use join, e.g.,

    tripIds.join(", ")
    

    Tangential

    If you want to create a list from another list you generally want something like map or collect as opposed to manually creating a list and appending to it, e.g. (untested):

    def sql = Sql.newInstance("jdbc:mysql://localhost:3306/steer", "root", "", "com.mysql.jdbc.Driver")
    def tripIds = sql.map { it.id }
    

    Or if you only care about the resulting string:

    def tripIds = sql.map { it.id }.join(", ")