filter

Filter the incoming elements using a predicate.

Simple operators

Signature

def filter(p: Out => Boolean): Repr[Out]

Description

Filter the incoming elements using a predicate. If the predicate returns true the element is passed downstream, if it returns false the element is discarded.

See also filterNot.

Example

For example, given a Source of words we can select the longer words with the filter operator:

Scala
val words: Source[String, NotUsed] =
  Source(
    ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt " +
    "ut labore et dolore magna aliqua.").split(" ").toList)

val longWords: Source[String, NotUsed] = words.filter(_.length > 6)

longWords.runForeach(println)
// consectetur
// adipiscing
// eiusmod
// tempor
// incididunt
Java
Source<String, NotUsed> words =
    Source.from(
        Arrays.asList(
            ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
                    + "ut labore et dolore magna aliqua.")
                .split(" ")));

Source<String, NotUsed> longWords = words.filter(w -> w.length() > 6);

longWords.runWith(Sink.foreach(System.out::print), system);
// consectetur
// adipiscing
// eiusmod
// tempor
// incididunt

Reactive Streams semantics

emits when the given predicate returns true for the element

backpressures when the given predicate returns true for the element and downstream backpressures

completes when upstream completes

API docs

Flow.filterFlow.filter

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.