簡體   English   中英

Java 8 Streams - 使用流將相同類型的多個對象映射到列表

[英]Java 8 Streams - Map Multiple Object of same type to a list using streams

是否有可能以更好的方式使用流來執行下面提到的步驟?

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

instanceDistribution.getStudentId()instanceDistribution.getTeacherId()都是Long類型。

有可能會提出這類問題,但我無法理解。 簡單的是或否。 如果是/否,那么如何和位解釋。 如果可能的話,請討論效率。

是的,您可以使用flatMapStream的單個元素映射到多個元素的Stream中,然后將它們展平為單個Stream

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

你可以使用3-args版本的collect:

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

您當前的版本可能會產生錯誤的結果,因為您在非線程安全集合中並行添加元素。 因此,您可能有多次在集合中具有相同的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM