Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 922
danilo Avatar asked Oct 08 '15 17:10

danilo


People also ask

How do you convert a list value to a comma separated String?

Approach: This can be achieved with the help of join() method of String as follows. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ', ' and the list as parameters. Print the String.

How do you split a String and store it in an ArrayList in Java?

split() method and Arrays. asList() method together to create an ArrayList from any delimited String, not just comma separated one. All you need to do is first split the given String on delimiter e.g. comma using the split() method, this will give you an array of String. Now, you can pass that array to Arrays.


1 Answers

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.

like image 90
Tim Avatar answered Sep 19 '22 19:09

Tim