Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create formatted string from ArrayList

Tags:

java

string

Consider following code:

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

My result here is (2134,3423,4234,343) as expected..

I do replace the last comma with the ending ) to get expected result. Is there a better way of doing this in general?

like image 930
StefanE Avatar asked Jan 12 '11 16:01

StefanE


4 Answers

You could use Commons Lang:

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

Alternatively, if you can't use external libraries:

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();
like image 156
Rob Hruska Avatar answered Nov 10 '22 10:11

Rob Hruska


Since Java 8 you can also do:

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());
like image 7
MrMeszaros Avatar answered Nov 10 '22 11:11

MrMeszaros


You will have to replace the last comma with a ')'. But use a StringBuilder instead of adding strings together.

like image 2
jzd Avatar answered Nov 10 '22 11:11

jzd


How about this from google-guava

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

System.out.println("("+JjoinedStr+")");
like image 2
Aravind Yarram Avatar answered Nov 10 '22 10:11

Aravind Yarram