Bazuka
Bazuka

Reputation: 417

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(", "))

Upvotes: 7

Views: 3970

Answers (2)

JB Nizet
JB Nizet

Reputation: 692191

You should be able to use collectingAndThen():

students.stream()
        .collect(groupingBy(Student::getTeacherName, 
                 mapping(Student::getName, 
                         collectingAndThen(toSet(), set -> String.join(", ", set)))))

Upvotes: 7

Reut Sharabani
Reut Sharabani

Reputation: 31339

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);

Upvotes: 1

Related Questions