简体   繁体   English

从ArrayList创建格式化字符串

[英]Create formatted string from ArrayList

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.. 我的结果是(2134,3423,4234,343)如预期的那样..

I do replace the last comma with the ending ) to get expected result. 我将最后一个逗号替换为结尾)以获得预期结果。 Is there a better way of doing this in general? 总的来说有更好的方法吗?

You could use Commons Lang : 你可以使用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();

Since Java 8 you can also do: Java 8开始,您还可以:

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

You will have to replace the last comma with a ')'. 你必须用')'替换最后一个逗号。 But use a StringBuilder instead of adding strings together. 但是使用StringBuilder而不是将字符串添加到一起。

How about this from google-guava 这个来自google-guava怎么样?

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

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

Building off Mateusz 's Java 8 example, there's an example in the StringJoiner JavaDoc that nearly does what OP wants. Mateusz的Java 8示例的基础上, StringJoiner JavaDoc中的一个示例几乎可以满足 OP的需求。 Slightly tweaked it would look like this: 略微调整它看起来像这样:

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

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

If you used an Iterator you could test hasNext() inside your loop to determine whether you needed to append a comma. 如果您使用了Iterator ,则可以在循环中测试hasNext()以确定是否需要附加逗号。

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(")");
for(int aValue : aList) {
    if (aValue != aList.Count - 1)
    {
          tmpString += aValue + ",";
    }
    else
    {
          tmpString += aValue + ")";
    }
}

Perhaps? 也许?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM