如何从两个来源过滤相同的元素

How to filter the same elements from two sources

有两个来源:

val s1 = Source(List(2, 4))
val s2 = Source(List(1, 2, 3, 4, 5))

如何过滤 s2 中存在于 s1 中的元素。对于上面的例子,它将是:

val s2Filtered = Source(List(1, 3, 5))

另一个用例:

val s1 = Source(List.empty[Int])
val s2 = Source(List(1, 2, 3, 4, 5))
val s2Filtered = Source(List(1, 2, 3, 4, 5)) // because s1 is empty

这不是一个很好的流式处理用例,因为您需要将第一个流完全耗尽到内存中才能执行此操作。 请注意,第一个流需要装入内存才能继续。

这是一种方法

  for{
    set  ← s1.runFold(Set.empty[Int]){case (set, n) ⇒ set + n}
    done ← s2.filter(set.contains).runForeach(println)
  } yield done