TransWikia.com

Convert Array to string in Java/Groovy

Stack Overflow Asked by maaz on January 26, 2021

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

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(", ")

Correct answer by Dave Newton on January 26, 2021

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

Answered by Sunil Kumar Sahoo on January 26, 2021

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"

Answered by Dónal on January 26, 2021

In groovy:

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

Answered by Mike Thomsen on January 26, 2021

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

Answered by AlexR on January 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP