Reputation: 43
I am using streams to concatenate a series of strings and add commas between them, but there must be no comma at the beginning or the end of the result string.
import java.util.Arrays;
import java.util.List;
public class QuestionNine {
public static void main(String[] args) {
new QuestionNine().launch();
}
public void launch(){
List<String> words = Arrays.asList("Hello", "Bonjour", "engine", "Hurray", "What",
"Dog", "boat", "Egg", "Queen", "Soq", "Eet");
String result = (words.stream().map(str -> str + ",").reduce("", (a,b) -> a + b));
result = result.substring(0, result.length() -1); //removes last comma
System.out.println(result);
}
}
Instead of using the String.substring()
method at the end to get rid of the last comma, is there a way i could have deleted the last comma within the stream pipeline?
Upvotes: 2
Views: 108
Reputation: 93842
The usual idiom is to use the joining Collector
with Streams.
String res = words.stream().collect(Collectors.joining(","));
Although you can use String.join
in your case since you are directly dealing with an Iterable
.
String res = String.join(",", words);
The problem with your approach is that the mapping function you apply impose that there will be a comma at the end of each word. You could get rid of this mapping; and apply the reduce function such that you get the desired output:
.stream().reduce("", (a,b) -> a.isEmpty() ? b : a+","+b);
but I don't recommend this.
Upvotes: 3
Reputation: 213261
Yes, you can use Collectors.joining()
here:
String joined = words.stream().collect(Collectors.joining(", "));
Or, also as noted from comments, you can use newly added String.join(CharSequence, Iterable)
method.
String joined = String.join(", ", words);
Upvotes: 0