在Java / groovy中将Array转换为字符串

时间:2012-01-10 11:36:29

标签: arrays string groovy

我有一个这样的清单:

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
        } 

现在打印三脚架给了我价值

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

现在我想将此列表转换为简单的字符串,如

 1,2,3,4,5,6

我该怎么做

5 个答案:

答案 0 :(得分:41)

使用join,例如,

tripIds.join(", ")

不相关,但如果您只想创建其他列表中的某些内容列表,那么最好不要执行mapcollect之类的操作,而不是手动创建列表并附加到它,不那么惯用,例如(另),

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

或者,如果关心结果字符串,

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

答案 1 :(得分:7)

在groovy中:

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

答案 2 :(得分:5)

使用Groovy加入收藏的join method

List l = [1,2,3,4,5,6]
assert l.join(',') == "1,2,3,4,5,6"

答案 3 :(得分:-1)

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

答案 4 :(得分:-2)

您可以尝试以下方法将列表转换为字符串

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

示例

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