Hi I'm trying to have a string represents concatenation of set of names for each teacher,
thus I need to use both Collectors.toSet
and Collectors.joining(", ")
how can I use them in 1 combine line ?
I can only make each one of them separately how can i do both of them ?
students.stream().collect(Collectors.groupingBy(student -> student.getTeacherName(), mapping(student -> student.getName(), toSet())
students.stream().collect(Collectors.groupingBy(student -> student.getTeacherName(), mapping(student -> student.getName(), joining(", "))
collect() is one of the Java 8's Stream API's terminal methods. It allows us to perform mutable fold operations (repackaging elements to some data structures and applying some additional logic, concatenating them, etc.) on data elements held in a Stream instance.
We can use Stream collect() function to perform a mutable reduction operation and concatenate the list elements. The supplier function is returning a new StringBuilder object in every call. The accumulator function is appending the list string element to the StringBuilder instance.
You should be able to use collectingAndThen()
:
students.stream()
.collect(groupingBy(Student::getTeacherName,
mapping(Student::getName,
collectingAndThen(toSet(), set -> String.join(", ", set)))))
I'm assuming you already know how to produce the set. We'll call it teacherSet
.
You want to re-stream after producing the set:
// create teacher set...
teacherSet.stream().collect(Collectors.joining(","));
You can also join after you're done producing the set using String.join
. Here is an example:
String.join(",", Arrays.stream("1,2,3,4,3,2,1".split(",")).collect(Collectors.toSet());
Or in your case:
// create teacher set...
String.join(",", teacherSet);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With