Convert Flux to List, Map - Reactor
Tags: reactor, reactive, java, spring
Published: 2020-12-18 09:48:49

Original Post: https://bezkoder.com/reactor-flux-list-map/

In this tutorial, I will show you ways to convert Flux into List/Map example that uses `collectList()`, `collectSortedList()`, `collectMap()`, `collectMultimap()` function..

## Ways to convert Flux into Collection
We will use `Flux` methods such as:

- `collectList()`: accumulate sequence into a `Mono<List>`.
- `collectSortedList()`: accumulate sequence and sort into a `Mono<List>`.
- `collectMap()`: convert sequence into a `Mono<Map>`.
- `collectMultimap()`: convert sequence into a `Mono<Map>` that each Map’s **key** can be paired with **multi-value** (in a `Collection`).

Then the `Mono` result above will be converted into a real List/Map using `block()` method.

## Declare & Initialize Flux
There are many ways to initialize a Flux, in this tutorial, we’re gonna use a simple way with `Flux.just()` function.
```java
Flux<String> flux = Flux.just(
						"Site_0:bezkoder.com", 
						"Description_0:Java Technology",
						"Description_1:Project Reactor");
```

## Convert Flux into List
### Flux collectList()
`collectList()` will accumulates sequence into a `Mono<List>`, then we use `block()` method to subscribe to the Mono and block indefinitely until a next signal is received.
```java
List<String> list1 = flux.collectList().block();
list1.forEach(System.out::println);
```
Result:
```
Site_0:bezkoder.com
Description_0:Java Technology
Description_1:Project Reactor
```

### Flux collectSortedList()
`collectSortedList()` accumulates sequence and **sort** into a `Mono<List>`, then we use `block()` method to subscribe to the `Mono` and block it.
```java
List<String> list2 = flux.collectSortedList().block();
list2.forEach(System.out::println);
```
Result:
```
Description_0:Java Technology
Description_1:Project Reactor
Site_0:bezkoder.com
```

## Convert Flux into Map
### Flux collectMap()
Function prototype:
```java
Mono<Map> collectMap(keyExtractor, valueExtractor)
```
– First, the function converts sequence into a `Mono<Map>`.
– Finally, the `Mono` becomes real List/Map by `block()` method.
```java
Map<String, String> map1 = flux
		.collectMap(
				item -> item.split(":")[0], 
				item -> item.split(":")[1])
		.block();
map1.forEach((key, value) -> System.out.println(key + " -> " + value));
```
Result:
```
Site_0 -> bezkoder.com
Description_1 -> Project Reactor
Description_0 -> Java Technology
```
### Flux collectMultimap()
Function prototype:
```java
Mono<Map<Object, Collection>> collectMultimap(keyExtractor, valueExtractor)
```
`collectMultimap()`: convert sequence into a `Mono<Map>` that each Map’s key can be paired with **multi-value** (in a `Collection`).

For example, we’re gonna get a Map with `Site` and `Description` as keys:
```java
Map<String, Collection<String>> map2 = flux
		.collectMultimap(
				item -> item.split("_[0-9]+:")[0], 
				item -> item.split(":")[1])
		.block();
map2.forEach((key, value) -> System.out.println(key + " -> " + value));
```
Check the result:
```
Site -> [bezkoder.com]
Description -> [Java Technology, Project Reactor]
```

## Implementation
### Technology
– Java 8
– Maven 3.6.1
– Reactor Core 3.4.0 with the 2020.0.1 release train.

### Source Code
```java
package com.bezkoder.reactor;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import reactor.core.publisher.Flux;

public class FluxCollection {
	public static void main(String[] args) {
		Flux<String> flux = Flux.just("Site_0:bezkoder.com", "Description_0:Java Technology",
				"Description_1:Project Reactor");

		System.out.println("=== flux.collectList() ===");
		List<String> list1 = flux.collectList().block();
		list1.forEach(System.out::println);

		System.out.println("\n=== flux.collectSortedList() ===");
		List<String> list2 = flux.collectSortedList().block();
		list2.forEach(System.out::println);

		System.out.println("\n=== flux.collectMap() ===");
		Map<String, String> map1 = flux
				.collectMap(
						item -> item.split(":")[0], 
						item -> item.split(":")[1])
				.block();
		map1.forEach((key, value) -> System.out.println(key + " -> " + value));

		System.out.println("\n=== flux.collectMultimap() ===");
		Map<String, Collection<String>> map2 = flux
				.collectMultimap(
						item -> item.split("_[0-9]+:")[0], 
						item -> item.split(":")[1])
				.block();
		map2.forEach((key, value) -> System.out.println(key + " -> " + value));
	}
}
```
The Result
```java
=== flux.collectList() ===
Site_0:bezkoder.com
Description_0:Java Technology
Description_1:Project Reactor

=== flux.collectSortedList() ===
Description_0:Java Technology
Description_1:Project Reactor
Site_0:bezkoder.com

=== flux.collectMap() ===
Site_0 -> bezkoder.com
Description_1 -> Project Reactor
Description_0 -> Java Technology

=== flux.collectMultimap() ===
Site -> [bezkoder.com]
Description -> [Java Technology, Project Reactor]
```

## Appendix: Getting Reactor
### Reactor installation in Maven
– First, import the BOM by adding the following to `pom.xml`:
```xml
<dependencyManagement> 
    <dependencies>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-bom</artifactId>
            <version>2020.0.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
```
– Next, add dependency:
```xml
<dependencies>
  <dependency>
    <groupId>io.projectreactor</groupId>
    <artifactId>reactor-core</artifactId>
  </dependency>
</dependencies>
```

### Reactor installation in Gradle
– First, apply the plugin from the Gradle Plugin Portal:
```
plugins {
  id "io.spring.dependency-management" version "1.0.7.RELEASE" 
}
```
– Next use dependency-management to import the BOM:
```
dependencyManagement {
  imports {
    mavenBom "io.projectreactor:reactor-bom:2020.0.1"
  }
}
```
– Finally, add dependency:
```
dependencies {
  implementation 'io.projectreactor:reactor-core' 
}
```
## Further Reading
- [Reactor 3 Reference Guide](https://projectreactor.io/docs/core/release/reference/)
- [Reactor Flux API](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html)