RxJava - groupBy、toMap 和 flatMap 不能很好地协同工作?

我希望这个小例子能打印出所有可以被 3 整除的数字。


@Test

public void test() {

    Observable.range(1, 100)

            .groupBy(n -> n % 3)

            .toMap(g -> g.getKey())

            .flatMap(m ->  m.get(0))

            .subscribe(System.out::println);

}

在println不打印任何东西,而是和我不知道为什么。


我从一个更复杂的例子中简化了这个例子,我知道这可以用不同的方式完成,但我需要这种方式,因为有更多的组需要同时操作flatMap。


绝地无双
浏览 241回答 3
3回答

慕的地6264312

使用该方法filter(Predicate<? super T> predicate)而不是groupBy(..)发出满足指定谓词的元素。Observable.range(1, 100)&nbsp; &nbsp; .filter(n -> n % 3 == 0)&nbsp; &nbsp; .toMap(g -> g.getKey())&nbsp; &nbsp; .flatMap(m ->&nbsp; m.get(0))&nbsp; &nbsp; .subscribe(System.out::println);Java Stream-API 的工作原理相同:IntStream.range(1, 100).filter(n -> n%3 == 0).forEach(System.out::println);// prints 3, 6, 9, 12... on the each line

隔江千里

该GROUPBY操作映射的输入源项目HashMap,其中最新的价值是关键下储存。引用文档:If more than one source item maps to the same key, the HashMap will contain the latest of those items.因此,在您的情况下,toMap运算符将输入序列转换为以下内容HashMap:&nbsp;{0=99, 1=100, 2=98}要从指定的范围中过滤掉所有不能被 3filter整除的数字,只需按照@Nikolas 的建议使用运算符即可。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python