Build a Java 8 Kit

Hi, I am trying to make a string a concatenation of a set of names for each teacher, so I need to use both Collectors.toSet and Collectors.joining(", ") , how can I use them in 1 combined string? I can only do each 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(", ")) 
+5
source share
2 answers

You can use collectingAndThen() :

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

I assume that you already know how to create a set. We will call him teacherSet .

You want to repeat the stream after creating the set:

 // create teacher set... teacherSet.stream().collect(Collectors.joining(",")); 

You can also join after you finish creating 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); 
0
source

Source: https://habr.com/ru/post/1245963/


All Articles