joining
joining()
joining() is a static method of Collectors that returns a Collector that concatenates the input elements with the specified delimiter. There are three variations of the joining() method:
Example
streamJoining()
public void streamJoining() {
List<String> stringList = Arrays.asList("zjc", "streams", "collectors");
System.out.println("Stream before modification - " + stringList);
Stream<String> stringStream = stringList.stream();
// concat the elements of the list using the joining method
String concatenatedString = stringStream.map(String::toUpperCase).collect(Collectors.joining());
// result after the concatenation
System.out.println(concatenatedString);
}
output
ZJCSTREAMSCOLLECTORS
joining(CharSequence delimiter)
Example
streamJoiningDelimiter()
public void streamJoiningDelimiter() {
List<String> stringList = Arrays.asList("zjc", "streams", "collectors");
System.out.println("Stream before modification - " + stringList);
Stream<String> stringStream = stringList.stream();
// delimiter to use
String delimiter = "-";
// concat the elements of the list using the joining method
String concatenatedString = stringStream.map(String::toUpperCase).collect(Collectors.joining(delimiter));
// result after the concatenation
System.out.println(concatenatedString);
}
output
ZJC-STREAMS-COLLECTORS
joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Example
streamJoiningDelimiterChars()
public void streamJoiningDelimiterChars() {
List<String> stringList = Arrays.asList("zjc", "streams", "collectors");
System.out.println("Stream before modification - " + stringList);
Stream<String> stringStream = stringList.stream();
// delimiter to use
String delimiter = "-";
// prefix to use
String prefix = "prefix-";
// suffix to use
String suffix = "-suffix";
// concat the elements of the list using the joining method
String concatenatedString = stringStream.map(String::toUpperCase).collect(Collectors.joining(delimiter, prefix, suffix));
// result after the concatenation
System.out.println(concatenatedString);
}
output
prefix-ZJC-STREAMS-COLLECTORS-suffix