How do I get string values from ArrayList and store them in a comma separated single string in Java 8?

I have an ArrayList with some strings I want to store the list of numbers in ArrayList in a single string separated by commas, as shown below

String s = "350000000000050287,392156486833253181,350000000000060764"

Here is my list:

List<String> e = new ArrayList<String>();

    e.add("350000000000050287");
    e.add("392156486833253181");
    e.add("350000000000060764");

I have been trying to achieve this by:

StringBuilder s = new StringBuilder();
    for (String id : e){

        s.append(id+",");

    }

The only problem is that this will add a comma at the end, which I don't want What is the best way?

thank you

Solution

The simplest solution is to use string join:

List<String> list = new ArrayList<String>();

list.add("11");
list.add("22");
list.add("33");

String joined = String.join(",",list);

System.out.println(joined);
//prints "11,22,33"

Note that this requires Java 8

However, if you want to support older versions of Java, you can fix the code using iterators:

StringBuilder sb = new StringBuilder();

Iterator<String> iterator = list.iterator();

// First time (no delimiter):
if (iterator.hasNext()) {
    sb.append(iterator.next());

    // Other times (with delimiter):
    while (iterator.hasNext()) {
        sb.append(",");
        sb.append(iterator.next());
    }
}

Or just use Boolean values to determine the first time:

StringBuilder sb = new StringBuilder();

boolean firstTime = true;

for (String str : list) {

    if (firstTime) {
        firstTime = false;
    } else {
        sb.append(",");
    }

    sb.append(str);
}

But the latter is obviously not as good as using iterators to compare the bytecode generated by each method However, as tagir valeev pointed out, this may not be true: this benchmark shows us that the performance of using flags is higher, with multiple iterations starting from 10

If anyone can explain why, I'm glad to know

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>