简体   繁体   中英

How to get String values from ArrayList and store them in a single string separated by commas, in Java 8?

I have an ArrayList with some Strings. I want to store that list of numbers from the ArrayList in a single string separated by a comma like the following.

String s = "350000000000050287,392156486833253181,350000000000060764"

This is my list:

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

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

I have been trying to do it the following way:

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

        s.append(id+",");

    }

The only problem with this is that this adds a comma to the end and I do not want that.What would be the best way to this?

Thanks

The easiest 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 could fix your code using an iterator:

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 simply use a boolean 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 should obviously be less performant than using an iterator comparing the generated bytecode per method. However, this might not be true as Tagir Valeev pointed out: this benchmark shows us that using a flag is more performant with a number of iterations starting from 10.

If anyone could explain why this is the case, I'd be glad to know.

Upvote for Tim for that Java 8 solution ;)

If you are not using JDK 8

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

        s.append(id).append(",");

    }
   String result =s.toString().replaceAll(",$", "");

The regex I used ",$" is to detect the last comma.

And also if you see, I'm replaced s.append(id +","); with s.append(id).append(","); for better performance

You can take a boolean flag to check first iteration, if not first iteration append "," before append id .

This may solve your problem.

boolean first = true;
for (String id : e){
    if(!first)
        s.append(",");
    else
        first = false;
    s.append(id);

}

NOTE

If you use Java8 then follow the solution of Tim.

Try iterating through your list by checking if the current index is last value of list (e.size-1), if it is not the last value, then concatenate the string as normal with ",", if it is, then concatenate without ",".

    List<String> e = new ArrayList<>(Arrays.asList("3333", "4444", "3333"));
    StringBuilder s = new StringBuilder();

    for (int i = 0; i < e.size(); i++) {
        s.append(e.get(i)).append((i == e.size() - 1) ? "" : ",");
    }
StringBuilder s = new StringBuilder();
for(int i = 0; i < e.size()-1; i++){
    s.append(e.get(i)+",")
}
s.append(e.get(i))

Collectors.joining(",") , work well in your case, example implementation:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Solution {
    public static void main(String[] args) {
        List<String> e = new ArrayList<>();
        e.add("350000000000050287");
        e.add("392156486833253181");
        e.add("350000000000060764");
        System.out.println(e.stream().collect(Collectors.joining(",")));
    }
}

Output:

350000000000050287,392156486833253181,350000000000060764

If we're talking about Java 8, how about:

Collection<String> e = asList("a", "b", "c");

String result = e.stream().collect(Collectors.joining(",")); // a,b,c

this method could be applied to any Collection of strings, as well as String.join() .

List<String> e = new ArrayList<String>();
    e.add("350000000000050287");
    e.add("392156486833253181");
    e.add("350000000000060764");
    Iterator iterator = e.iterator();
    String s="";
    int i = 1;
    while (iterator.hasNext()) {
        if (i == e.size()) {
            s =s+iterator.next();
        } else {
            s =s+iterator.next()+",";
        }
        i++;
    }
    System.out.println(s);

350000000000050287,392156486833253181,350000000000060764

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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