Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<String> to delimited String [duplicate]

Tags:

java

string

list

Possible Duplicate:
Java: convert List<String> to a join()d string

Having this:

List<String> elementNames = Arrays.asList("h1", "h2", "h3", "h4", "h5", "h6");

What is an elegant way to get String with a custom delimiter, like so:

"h1,h2,h3,h4,h5,h6"
like image 657
Alp Avatar asked Jun 05 '11 18:06

Alp


People also ask

How do you convert a List 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 I convert a List to a single String?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I convert a String to a List of strings?

How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.


2 Answers

StringBuilder sb = new StringBuilder();

for(String s: elementnames) {
   sb.append(s).append(',');
}

sb.deleteCharAt(sb.length()-1); //delete last comma

String newString = sb.toString();

Update: Starting java 8, you can obtain the same results using:

    List<String> elementNames = Arrays.asList("1", "2", "3");

    StringJoiner joiner = new StringJoiner(",", "", "");
    elementNames.forEach(joiner::add);

    System.out.println(joiner.toString());
like image 147
gouki Avatar answered Sep 22 '22 02:09

gouki


If you don't mind using the StringUtils library provided by apache, you could do:

// Output is "a,b,c"
StringUtils.join(["a", "b", "c"], ','); 

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

like image 23
debracey Avatar answered Sep 25 '22 02:09

debracey