RxJava:如何在序列中找到较小的数字



我试图在使用RxJava的序列中找到较小的数字。这是我第一次尝试解决这个任务。它工作(我得到1作为结果),但因为我仍然是一个新手在RxJava我百分之百肯定有一个更好的解决方案:

    Observable<List<Integer>> sequence = Observable.create(new Observable.OnSubscribe<List<Integer>>() {
        @Override
        public void call(Subscriber<? super List<Integer>> subscriber) {
            subscriber.onNext(Arrays.asList(new Integer[]{10, 9, 8, null, 1, 2, 3, 4}));
            subscriber.onCompleted();
        }
    });
    final int[] minValue = {Integer.MAX_VALUE};
    sequence.flatMap(numList -> Observable.from(numList))
            .filter(number -> number != null)
            .filter(number -> {
                if (number < minValue[0]) {
                    minValue[0] = number;
                    return true;
                } else {
                    return false;
                }
            })
            .last()
            .subscribe(number -> {
                Log.i("App", "The smaller value in the sequence is " + number);
            });

有什么好的建议吗?:)

使用rxjava-math模块,min()运算符将执行您想要的操作。

sequence
    .flatMap(numList -> Observable.from(numList)
    .filter(number -> number != null)
    .min()
    .subscribe(number -> {
        Log.i("App", "The smaller value in the sequence is " + number);
    });

你也可以使用reduce()滚动你自己版本的min()

sequence
    .flatMap(numList -> Observable.from(numList)
    .filter(number -> number != null)
    .reduce(Integer.MAX_VALUE, 
        (currentMin, number) -> number < currentMin ? number : currentMin)
    .filter(number -> number != Integer.MAX_VALUE)
    .subscribe(number -> {
        Log.i("App", "The smaller value in the sequence is " + number);
    });

相关内容

  • 没有找到相关文章

最新更新