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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8802647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:21:01  来源:igfitidea点击:

Convert Array to string in Java/ groovy

arraysstringgroovy

提问by maaz

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

现在打印tripids给了我价值

  [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

我该怎么做

回答by Dave Newton

Use join, e.g.,

使用join,例如,

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 mapor collectinstead of manually creating a list and appending to it, which is less idiomatic, e.g. (untested),

不相关,但如果您只想从另一个列表中创建一个列表,您最好执行类似 amapcollect而不是手动创建列表并附加到它的列表,这不太惯用,例如(未经测试),

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

Or if you onlycare about the resulting string,

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

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

回答by Mike Thomsen

In groovy:

在常规中:

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

回答by Dónal

Use the join methodthat Groovy addes to Collection

使用Groovy 添加到 Collection的join 方法

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

回答by AlexR

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

回答by Sunil Kumar Sahoo

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