В реактивном java как собрать все элементы из потока, только если значение элемента такое же, как первое - PullRequest
0 голосов
/ 09 июля 2020

У меня есть Flux<Integer>

, теперь я хочу собрать все элементы из этого потока, где currentElement <= firstElement </p>

Учитывая, что у меня есть Flux.from(5, 6, 4, 7, 3), я хочу иметь 5,4,3 в получившемся наборе

Ответы [ 2 ]

0 голосов
/ 09 июля 2020

См. 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-

0 голосов
/ 09 июля 2020

Вот что вы можете сделать: выберите первый элемент из потока.

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

Затем используйте этот элемент для подготовки предиката фильтра.

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