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
        } 

now on printing tripids gives me value

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

now i want to convert this list to simple string like

 1,2,3,4,5,6

How can i do it

share|improve this question

71% accept rate
feedback

5 Answers

up vote 5 down vote accepted

Just use join:

tripIds.join(", ")
share|improve this answer
feedback

In groovy:

def myList = [1,2,3,4,5]
def asString = myList.join(", ")
share|improve this answer
feedback

Use the join method that Groovy addes to Collection

List l = [1,2,3,4,5,6]
assert l.join(',') == "1,2,3,4,5,6"
share|improve this answer
feedback

you can try the following approach to convert list into String

StringBuffer sb = new StringBuffer();
    for (int i=0; i<tripIds.size(); i++)
    {
        if(i!=0){
        sb.append(",").append(tripIds.get(i));
        }else{
            sb.append(tripIds.get(i));
        }
    }
    String listInString = sb.toString();
    System.out.println(listInString);

Example

ArrayList<String> tripIds = new ArrayList<String>();
        tripIds.add("a");
        tripIds.add("b");
        tripIds.add("c");
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<tripIds.size(); i++)
        {
            if(i!=0){
            sb.append(",").append(tripIds.get(i));
            }else{
                sb.append(tripIds.get(i));
            }
        }
        String listInString = sb.toString();
        System.out.println(listInString);
share|improve this answer
Seems like a lot of work. Why repeat the code for appending tripIds.get(i) in both conditions? For that matter, why show the code for doing the creation twice; wouldn't it be more vertical-space-friendly to put it in a method and just call it from the example? – Dave Newton Jan 10 at 12:48
I assume you get paid by the line? – Don Jan 10 at 15:49
feedback
String str = tripIds.toString();
str = str.substring(1, str.length() - 1);
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.