2012-01-10 28 views
16

Ho una lista come questa:Convert Array di stringhe in Java/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 
     } 

ora in tripids stampa mi dà stimo

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

ora voglio convertire questo elenco per semplice stringa come

1,2,3,4,5,6 

Come posso farlo

risposta

30

Usa join, ad esempio,

tripIds.join(", ") 

non collegati, ma se si desidera solo per creare un elenco di qualcosa da un altro elenco, si sarebbe meglio fare qualcosa di simile a un map o collect invece di creare manualmente un elenco e aggiungerlo ad esso, che è meno idiomatico, ad es (Non testato),

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

O se solo a cuore la stringa risultante,

def tripIds = sql.map { it.id }.join(", ") 
-1
String str = tripIds.toString(); 
str = str.substring(1, str.length() - 1); 
6

in Groovy:

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

Utilizzare il join method che Groovy addes alla Collezione

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

si può provare il seguente approccio per convertire in lista 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); 

Esempio

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

sembra un sacco di lavoro. Perché ripetere il codice per l'aggiunta di 'tripIds.get (i)' in entrambe le condizioni? Del resto, perché mostrare il codice per fare la creazione due volte; non sarebbe più adatto allo spazio verticale metterlo in un metodo e basta chiamarlo dall'esempio? –

+3

Immagino che vieni pagato dalla linea? –