简体   繁体   English

Java ArrayList StringBuilder追加

[英]Java ArrayList StringBuilder appending

I have one problem when appending List values as String. 将List值附加为String时遇到一个问题。 I will be getting 1 or more than 1 value into the list. 我将在列表中获得1个或超过1个值。 Then I need to append these string as one string and use a separator , for each string. 然后,我需要将这些字符串附加为一个字符串,并对每个字符串使用一个分隔符。 But at the end also the comma is getting added. 但最后也增加了逗号。 How Can I remove this at the end of the string dynamically. 如何动态删除此字符串的末尾。 Here is my code: 这是我的代码:

cntList = parseXml(metadata.xml);
if (cntList.size() != 0) {
    // entryCountryMap.put(id, country);
    System.out.println("Size is  ---->" + cntList.size());
    StringBuilder sb = new StringBuilder();
    if (cntList.size() >= 2) {
        for (String s : cntList) {
            sb.append(s);
            sb.append(",");
        }
    }
    System.out.println("StringBuilder ----->" + sb.toString());
}

And my output is like this: 我的输出是这样的:

StringBuilder ----->All Countries,US - United States,

Please help me resolving this. 请帮我解决这个问题。 Thanks - Raji 谢谢-拉吉

With java 8 it's a one liner 使用Java 8只需一根衬纸

String.join(",", cntList);

If you need to filter the elements of the list and/or mutate the strings before joining to a single string, you can still do it in a very concise manner without loops. 如果您需要在连接到单个字符串之前过滤列表的元素和/或更改字符串,则仍然可以以非常简洁的方式执行此操作,而无需循环。

cntList.stream().filter(...).map(...).collect(Collectors.joining(","));

(the ... need to be replaced by your filtering predicate and your mapper) ...需要替换为您的过滤谓词和映射器)

I would use normal for loop. 我会使用正常for循环。 The last one append outside the for loop without comma for循环外的最后一个追加,不带逗号

if (cntList.size() >= 2) {
    for (int i=0;i<cntList.size()-1;i++) {
        sb.append(cntList.get(i));
        sb.append(",");
    }
    sb.append(cntList.get(cntList.size()-1));
}

Simply delete the last character: 只需删除最后一个字符:

StringBuilder sb = new StringBuilder("foo,");
System.out.println(sb.deleteCharAt(sb.length() - 1)); 

Output 输出量

foo

More dynamically, you can find the last comma by index and delete that plus anything that comes after: 更动态地,您可以按索引查找最后一个逗号,然后删除该逗号以及后面的所有内容:

sb.delete(sb.lastIndexOf(","), sb.length());

As Pshemo points out: 正如Pshemo指出的那样:

sb.setLength(sb.length() - 1); will actually perform better than sb.deleteCharAt(sb.length() - 1) . 实际上将比sb.deleteCharAt(sb.length() - 1)表现更好。

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

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