在Java / Groovy中将数组转换为字符串

Convert Array to string in Java/ groovy

我有一个这样的清单:

1
2
3
4
5
6
7
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
  [1,2,3,4,5,6,]

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

1
 1,2,3,4,5,6

我该怎么做


使用join,例如

1
tripIds.join(",")

无关,但是如果您只想从另一个列表中创建一个列表,则最好做一个mapcollect之类的操作,而不是手动创建一个列表并将其附加到列表上,这是比较惯用的, 例如 (未测试),

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

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

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

时髦:

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


使用Groovy添加到Collection的join方法

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

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

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

1
2
3
4
5
6
7
8
9
10
11
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);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);