7

I have a set of Strings that I want to combine into one String with all sentences separated with a coma (",") like in a .csv file.

Here is my code:

String dataContainer;

for (String tempString : setInput) {
    String finalString = "," + tempString + ",";   
}

This doesn't work with me :(

But it should do for Set e.g.:

Set<String> setInput = new TreeSet();
setInput.add("Dog");
setInput.add("Cat");
setInput.add("Mouse");

to produce the String:

,Dog,,Cat,,Mouse,
3
  • 3
    You really want 2 commas? Commented Sep 11, 2013 at 12:01
  • what do you mean by: This doesn't work for me Commented Sep 11, 2013 at 12:12
  • Given your inputs, how do you expect those extra commas to appear? Commented Sep 1, 2020 at 12:11

7 Answers 7

17

It is better to use StringBuilder

StringBuilder sb = new StringBuilder();

for(String tempString:setInput){
    sb.append(",").append(tempString).append(",");   
}
Sign up to request clarification or add additional context in comments.

6 Comments

or even sb.append(",").append(tempString).append(",");
@Pshemo yes, it is better. I added your suggestion.
+1 you can delete last inserted comma using sb.deleteCharAt(sb.lastIndexOf(",")); if it is not necessary
code for removing of last delimiter (comma in this case) doesn't looks kind of old school, I would suggest StringJoiner or StringJoiner through java streams as I mentioned in the answer below. That has nice aesthetics :)
@Rituraj it is up to you to decide. if you are going for Java 8 yes. you can. This question originally posted even before Java 8.
|
8

Or we can use Java 8 Stream

String joined = Stream.of("A", "B", "C").collect(Collectors.joining("delimiter", "prefix", "suffix"));

Or use the StringJoiner class

Directly Use StringJoiner class

Or the StringBuilder class

new StringBuilder().add("A").add("B").toString()

Comments

6

What You are doing is intializing your result string each time.

Actually ,you want to do

String finalString ="";
for(String tempString:setInput){
      finalString += "," + tempString + "," ;   
}

But the above approach causes multiple String creations.

But I suggest to go for StringBuilder.

 StringBuilder finalStringb =new StringBuilder();
    for(String tempString:setInput){
          finalStringb.append(",").append(tempString).append(",") ;   
    }

String finalS = finalStringb.toString();

1 Comment

String finalS = finalStringb.toString() really helps me!
4

Maybe you are looking only for

String csvString = "," + String.join(",,", string1, string2, string3) +"," ;

Reference

2 Comments

Won't match the desired output of ,Dog,,Cat,,Mouse,.
Okay so String csvString = "," + String.join(",,", string1, string2, string3) +"," ;
4

Solution 1: (If you don't need a delimiter)


I would recommend using concat(Object... objects) from org.assertj.core.util.String.

public static String concat(Object... objects) {
    return Arrays.isNullOrEmpty(objects) ? null : (String)java.util.Arrays.stream(objects).map(String::valueOf).collect(Collectors.joining());
}

You can use it like this:

  concat("string1", "string2", "string3", "string4");

Solution 2 using StringJoiner (Java 8+):


This is from java.util. You even have the option to specify a prefix and suffix.

StringJoiner stringJoiner = new StringJoiner(", ");
 
stringJoiner.add("string1");
stringJoiner.add("string2");
stringJoiner.add("string3");
 
assertEquals("string1, string2, string3", stringJoiner.toString());

Solution 3 using Collectors.joining (Java 8+):


This is a functionality from Java 8 Stream API.

List<String> stringList = Arrays.asList("string1", "string2", "string3");
 
String concatString = stringList.stream().collect(Collectors.joining(", "));
 
assertEquals("string1, string2, string3", concatString);

Comments

2

Alternatively, if you are using Java 8, you could try something like this:

public static String join(final Set<String> set){
    return new StringBuilder(",").append(set.stream().collect(Collectors.joining(",,"))).append(",").toString();
}

public static void main(String args[]){
    Set<String> setInput = new TreeSet<>();
    setInput.add("Dog");
    setInput.add("Cat");
    setInput.add("Mouse");
    System.out.println(join(setInput));
}

The output is:

,Cat,,Dog,,Mouse,

Although, I'm a little unsure to why you would want 2 commas in between each element and a comma at the start and end. If you just want one comma separating each element (and no comma at the start or end), modify the join(Set<String>) to look like this:

public static String join(final Set<String> set){
    return set.stream().collect(Collectors.joining(",")); //change "," to ", " for spacing
}

After doing so, the new output would be:

Cat,Dog,Mouse

Comments

1

org.apache.commons.lang.StringUtils.join() can come in handy

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.