Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
maaz Avatar asked Jan 10 '12 11:01

maaz


People also ask

How do you put an array into a string?

Using StringBufferCreate an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.


2 Answers

Use join, e.g.,

tripIds.join(", ") 

Unrelated, but if you just want to create a list of something from another list, you'd be better off doing something like a map or collect instead of manually creating a list and appending to it, which is less idiomatic, 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(", ") 
like image 131
Dave Newton Avatar answered Sep 16 '22 14:09

Dave Newton


In groovy:

def myList = [1,2,3,4,5] def asString = myList.join(", ") 
like image 38
Mike Thomsen Avatar answered Sep 18 '22 14:09

Mike Thomsen