joining strings in java

code

 

Joining a list of string by a delimiter has been greatly simplified in Java 8. The introduction of the "join" method to the "String" class makes this possible.

List<String> strings = new LinkedList<>();
strings.add("Java");
strings.add("is");
strings.add("cool");
String message = String.join(" ", strings);
//message returns : Java is cool

Set<String> strings1 = new LinkedHashSet<>();
strings1.add("Java");
strings1.add("is");
strings1.add("very");
strings1.add("cool");
String message = String.join("-", strings1);
//message returns : Java-is-very-cool

 

Another way you could join strings in java, is by using the Collectors joining method

List<Group> groups = Arrays.asList(
new Group("a","The a group"),
new Group("b","The b group"),
new Group("c","The c group"),
new Group("d","The d group")
);

String joinedNames = groups.stream().map(Group::getName).collect(Collectors.joining(", "));