Java 8 Streams - mapping multiple objects of the same type to a list using streams

Is it possible to follow the steps below using streams better?

Set<Long> memberIds = new HashSet<>();
marksDistribution.parallelStream().forEach(marksDistribution -> {
        memberIds.add(marksDistribution.getStudentId());
        memberIds.add(marksDistribution.getTeacherId());
      });

instanceDistribution.getStudentId()and instanceDistribution.getTeacherId()- both types Long.

Perhaps such a question will be asked, but I cannot understand it. In simple yes or no. If yes / no, then like a bit to explain. And if possible, discuss the effectiveness.

+4
source share
2 answers

You can use the 3-args version of collect:

Set<Long> memberIds = 
    marksDistribution.parallelStream()
                     .collect(HashSet::new, 
                              (s, m) -> {
                                   s.add(m.getStudentId());
                                   s.add(m.getTeacherId());
                               }, Set::addAll);

, - . , , .

+4

, flatMap Stream Stream , Stream:

Set<Long> memberIds = 
    marksDistribution.stream()
                     .flatMap (marksDistribution -> Stream.of(marksDistribution.getStudentId(), marksDistribution.getTeacherId()))
                     .collect(Collectors.toSet());
+6

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


All Articles