How to transform Flux and Mono in Java?
We often have to transform the data we receive from one source to send it to another. In the project Reactor, we use the operators to transform Mono and Flux.
What are operators in Project Reactor?
Operators in Project Reactor are functions that we can call in a chain, just like operators in Java 8 Streams. We use them to convert the input to the desired output.
In this post, we will explore the following operators:
- map()
- filter()
- flatMap()
Working with the Reactive Streams operators
Let’s see some examples where we use the above mentioned operators:
map() operator
Let’s say we have a Flux that contains some names. We want to transform each name into an uppercase. We can do that using the map() operator:
class ReactiveJavaTutorial { public static void main(String[] args) { Flux.fromArray(new String[]{"Tom", "Melissa", "Steve", "Megan"}) .map(String::toUpperCase) .subscribe(System.out::println); } }
Remember: we need to subscribe in order to consume data from the Publisher.
filter() operator
Now, we have a requirement to convert only names whose length is >5. For this, we will use the filter() operator together with map():
class ReactiveJavaTutorial { public static void main(String[] args) { Flux.fromArray(new String[]{"Tom", "Melissa", "Steven", "Megan"}) .filter(name -> name.length() > 5) .map(String::toUpperCase) .subscribe(System.out::println); } }
class ReactiveJavaTutorial { public static void main(String[] args) { Flux<String> flux = Flux.fromArray(new String[]{"Tom", "Melissa", "Steven", "Megan"}); Flux<String> transformedFlux = flux.map(String::toUpperCase); System.out.println("New Flux:"); transformedFlux.subscribe(name -> System.out.print(name + " ")); System.out.println(); System.out.println("Original Flux:"); flux.subscribe(name -> System.out.print(name + " ")); } }
flatMap() operator
The flatMap() operator transforms one source element to a Flux of 1 … n elements. We use flatMap() when the transformation returns a Flux or Mono.
Let’s call a function that returns a Mono with the map() operator:
class ReactiveJavaTutorial { public static void main(String[] args) { Flux.fromArray(new String[]{"Tom", "Melissa", "Steven", "Megan"}) .map(ReactiveJavaTutorial::putModifiedNameIntoMono) .subscribe(System.out::println); } private static Mono<String> putModifiedNameIntoMono(String name) { return Mono.just(name.concat(" modified")); } }
class ReactiveJavaTutorial { public static void main(String[] args) { Flux.fromArray(new String[]{"Tom", "Melissa", "Steven", "Megan"}) .flatMap(ReactiveJavaTutorial::putModifiedNameIntoMono) .subscribe(System.out::println); } private static Mono<String> putModifiedNameIntoMono(String name) { return Mono.just(name.concat(" modified")); } }