filter

Filter the incoming elements using a predicate.

Simple operators

Signature

Source.filterSource.filter Flow.filterFlow.filter

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
sourceval 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
// incididunt
Java
sourceSource<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.runForeach(System.out::println, system);
// consectetur
// adipiscing
// eiusmod
// 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.