StringJoiner is the goto class when it comes to joining multiple objects with a delimiter. Let us take a look at how to convert a Java Collection to a StringJoiner object.
Example:
package org.code2care.examples;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public class StringJoinerCollectionsExample {
public static void main(String[] args) {
List<String> countriesList = new ArrayList<>();
countriesList.add("Japan");
countriesList.add("USA");
countriesList.add("China");
countriesList.add("France");
StringJoiner stringJoiner = new StringJoiner(",");
for (String country : countriesList) {
stringJoiner.add(country);
}
System.out.println("Countries: " + stringJoiner.toString());
}
}
Output:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!