Java 8 thread collection kits

I have two cards, namely

Map<String, Set<String>> courseTeacherMap = {course1: [teacher1, teacher2], ...} Map<String, Set<String>> teacherStudentMap = {teacher1: [student1, student2], ...} 

And I defined a courseStudentPair class that has a very simple structure

 public class courseStudentPair{ String studentName; // Taken from teacherStudentMap String courseName; // Taken from courseTeacherMap } 

And my goal is to deduce Set<courseStudentPair> from two maps. While teacher A teaches course C, every student who is in the set of key A values ​​in teacherStudentMap is considered a student taking C.

For example, given

 Map<String, Set<String>> courseTeacherMap = {c1: [t1], c2:[t2], c3:[t1, t2]} Map<String, Set<String>> teacherStudentMap = {t1: [s1], t2:[s1, s2]} 

The result should be * (student, course) means the courseStudentPair object in the example below *

 Set<courseStudentPair> result = [(c1, s1), (c2, s1), (c2, s2), (c3, s1), (c3, s2)] 

This is pretty easy to do for loops, but I'm learning the flow function in Java 8, and it seems pretty complicated to me. You can assume that the courseStudentPair class has a constructor or constructor.

+5
source share
2 answers

In the same spirit, you can create each combination (course, teacher), and then look for students associated with this teacher. This can generate duplicates (e.g. c3, s1), so make sure your CourseStudentPair class implements equals() and hashCode() based on these two fields.

 import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; ... Set<CourseStudentPair> result = courseTeacherMap.entrySet() .stream() .flatMap(e -> e.getValue() .stream() .flatMap(t -> teacherStudentMap.getOrDefault(t, emptySet()).stream().map(s -> new CourseStudentPair(e.getKey(), s)))) .collect(toSet()); /* Output: CourseStudentPair{studentName='c1', courseName='s1'} CourseStudentPair{studentName='c2', courseName='s2'} CourseStudentPair{studentName='c2', courseName='s1'} CourseStudentPair{studentName='c3', courseName='s2'} CourseStudentPair{studentName='c3', courseName='s1'} */ 
+2
source
 List<Pair<String, String>> result = courseTeacherMap.entrySet() .stream() .flatMap(entry -> Optional.ofNullable(entry.getValue()) .orElse(new HashSet<>()) .stream() .flatMap(teacher -> Optional.ofNullable(teacherStudentMap.get(teacher)) .orElse(new HashSet<>()) .stream() .map(student -> Pair.of(entry.getKey(), student)))) .distinct() .collect(Collectors.toList()); 

I edited to make it null if the teacher has no students, for example, or your Map may have a key mapped to zero, for example.

+1
source

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


All Articles