36

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?

5 Answers 5

62

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(", ")
Sign up to request clarification or add additional context in comments.

Comments

17

In groovy:

def myList = [1,2,3,4,5]
def asString = myList.join(", ")

Comments

11

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"

Comments

-1
String str = tripIds.toString();
str = str.substring(1, str.length() - 1);

Comments

-3

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);

2 Comments

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?
I assume you get paid by the line?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.