Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect to set with joining Java 8

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(", "))
like image 693
Bazuka Avatar asked Mar 29 '16 06:03

Bazuka


People also ask

What does collect () do in Java?

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.

How do you collect Stream strings?

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.


2 Answers

You should be able to use collectingAndThen():

students.stream()
        .collect(groupingBy(Student::getTeacherName, 
                 mapping(Student::getName, 
                         collectingAndThen(toSet(), set -> String.join(", ", set)))))
like image 119
JB Nizet Avatar answered Oct 21 '22 01:10

JB Nizet


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);
like image 31
Reut Sharabani Avatar answered Oct 21 '22 02:10

Reut Sharabani