liveBook · Manning

Distinct keyword

As explained in Spring in Action, Sixth Edition

distinct is a Project Reactor operator that emits each distinct source element only once.

Use distinct() when a Flux may publish the same value more than once but you want each value only once in the resulting Flux. Unlike filter(), which needs a Predicate to decide what passes through, distinct() filters out values already published. section 11.3.3

@Test
public void distinct() {
  Flux<String> animalFlux = Flux.just(
      "dog", "cat", "bird", "dog", "bird", "anteater")
      .distinct();
  
  StepVerifier.create(animalFlux)
      .expectNext("dog", "cat", "bird", "anteater")
      .verifyComplete();
}

The source publishes "dog" and "bird" twice. After distinct(), StepVerifier expects each only once: "dog", "cat", "bird", then "anteater". section 11.3.3

How Spring in Action, Sixth Edition covers it

How deep it goes
Defines the operator through its output and a verified example, without explaining its internals.
Examples
Tests a Flux of animal names in which repeated "dog" and "bird" values appear only once in the expected output.
What it assumes
Uses Java Flux.just() and StepVerifier syntax while showing the source values and expected output directly.
What you can do after
Apply it via Project Reactor’s distinct() and verify the resulting Flux with StepVerifier.
How it connects
Contrasts duplicate removal with Predicate-based filter() and places it among Flux filtering operations.

Also explained in

Compare how 4 books explain distinct keyword →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.