a3dsfcv
a3dsfcv

Reputation: 1274

In reactive java how to collect all elements from flux, only if element value the same as first

I have a Flux<Integer>

now I want to collect all elements from this flux where currentElement <= firstElement

Given I have a Flux.from(5, 6, 4, 7, 3), I want to have 5,4,3 in the resulting set

Upvotes: 1

Views: 6327

Answers (2)

Artem Bilan
Artem Bilan

Reputation: 121177

See Flux.switchOnFirst():

 * Transform the current {@link Flux<T>} once it emits its first element, making a
 * conditional transformation possible. This operator first requests one element
 * from the source then applies a transformation derived from the first {@link Signal}
 * and the source. The whole source (including the first signal) is passed as second
 * argument to the {@link BiFunction} and it is very strongly advised to always build
 * upon with operators (see below).

https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#switchOnFirst-java.util.function.BiFunction-

Upvotes: 3

Govinda Sakhare
Govinda Sakhare

Reputation: 5729

Here's what you can do, pick the first element from flux.

Flux<Integer> flux = Flux.just(5, 9, 8, 4, 3, 6);
Integer firstElement = flux.blockFirst();

Then use that element to prepare the filter predicate.

List<Integer> numbers = flux.toStream()
               .filter(num -> num <= firstElement)
               .collect(Collectors.toList());

Upvotes: 4

Related Questions