Collectors.joining example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Person{
private String name;
Person(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class CollectorJoiningFlight {
public static void main(String[] dataBag) {
Stream<String> strings = Stream.of("Vikram","Ashok","Pratap");
String strs = strings.collect(Collectors.joining(","));
System.out.println("Joined String: "+strs);
List<Person> persons= Arrays.asList(
new Person("raj"),
new Person("rose"),
new Person("jack")
);
String names = persons
.stream()
.map(Person::getName)
.collect(Collectors.joining(","));
System.out.println("Names: "+names);
}
}
Output:
Joined String: Vikram,Ashok,Pratap
Names: raj,rose,jack
Explanation:
joining internally uses StringBuilder to append the strings into
one string.
Collectors.joining(","): Returns a Collector that concatenates the input elements, separated by the given delimiter, in obtained order. Here we have used comma(,) delimiter.