2011-01-12 20 views
8

Considere el siguiente código:cadena con formato de ArrayList

ArrayList<Integer> aList = new ArrayList<Integer>(); 
    aList.add(2134); 
    aList.add(3423); 
    aList.add(4234); 
    aList.add(343); 

    String tmpString = "("; 

    for(int aValue : aList) { 
     tmpString += aValue + ","; 
    } 
    tmpString = (String) tmpString.subSequence(0, tmpString.length()-1) + ")"; 

    System.out.println(tmpString); 

Mi resultado aquí es (2134,3423,4234,343) como se esperaba ..

hago sustituir la última coma con la terminación) para obtener el resultado esperado ¿Hay una mejor manera de hacer esto en general?

Respuesta

15

Usted podría utilizar Commons Lang:

String tmpString = "(" + StringUtils.join(aList, ",") + ")"; 

bibliotecas Alternativamente, si no se puede utilizar externos:

StringBuilder builder = new StringBuilder("("); 
for (int aValue : aList) builder.append(aValue).append(","); 
if (aList.size() > 0) builder.deleteCharAt(builder.length() - 1); 
builder.append(")"); 
String tmpString = builder.toString(); 
+0

Prefiero el enfoque de Commons Lang también, especialmente porque lo tengo como una dependencia en todos los proyectos de todos modos. –

+0

Por lo general, termino usándolo por una razón u otra también. No hay razón para reinventar la rueda a menos que tenga restricciones específicas que le impidan usar bibliotecas externas. Algunas de las bibliotecas de Apache Commons tienen sus inconvenientes cuando se trata de colecciones y genéricos, pero StringUtils es bastante sencillo. –

+0

¡Solución muy buena! Sabía que debe haber una manera de hacer esto en un trazador de líneas. Y la lib de StringUtils es casi estándar para incluir de todos modos. – StefanE

-1
for(int aValue : aList) { 
    if (aValue != aList.Count - 1) 
    { 
      tmpString += aValue + ","; 
    } 
    else 
    { 
      tmpString += aValue + ")"; 
    } 
} 

¿Quizás?

+0

aList.size() es el correcto. – pringlesinn

2

Usted tendrá que reemplazar la última coma con un ')'. Pero use un StringBuilder en lugar de agregar cadenas juntas.

2

¿Qué tal esto desde google-guava

String joinedStr = Joiner.on(",").join(aList); 

System.out.println("("+JjoinedStr+")"); 
0

Si utilizó un Iterator podría probar hasNext() dentro de su bucle para determinar si se necesitaba para añadir una coma.

StringBuilder builder = new StringBuilder(); 
builder.append("("); 

for(Iterator<Integer> i=aList.iterator(); i.hasNext();) 
{ 
    builder.append(i.next().toString()); 
    if (i.hasNext()) builder.append(","); 
} 

builder.append(")"); 
4

Desde Java 8 también se puede hacer:

ArrayList<Integer> intList = new ArrayList<Integer>(); 
intList.add(2134); 
intList.add(3423); 
intList.add(4234); 
intList.add(343); 

String prefix = "("; 
String infix = ", "; 
String postfix = ")"; 

StringJoiner joiner = new StringJoiner(infix, prefix, postfix); 
for (Integer i : intList) 
    joiner.add(i.toString()); 

System.out.println(joiner.toString()); 
1

Construido a partir de Java 8 ejemplo Mateusz 's, hay un ejemplo en el JavaDoc StringJoiner que casi hace lo que quiere OP. Un poco ajustado tendría este aspecto:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4); 

String commaSeparatedNumbers = numbers.stream() 
    .map(i -> i.toString()) 
    .collect(Collectors.joining(",","(",")"));