3 回答

TA贡献1817条经验 获得超6个赞
使用该方法filter(Predicate<? super T> predicate)而不是groupBy(..)发出满足指定谓词的元素。
Observable.range(1, 100)
.filter(n -> n % 3 == 0)
.toMap(g -> g.getKey())
.flatMap(m -> m.get(0))
.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

TA贡献1906条经验 获得超10个赞
该GROUPBY操作映射的输入源项目HashMap,其中最新的价值是关键下储存。
引用文档:
If more than one source item maps to the same key, the HashMap will contain the latest of those items.
因此,在您的情况下,toMap运算符将输入序列转换为以下内容HashMap:
{0=99, 1=100, 2=98}
要从指定的范围中过滤掉所有不能被 3filter整除的数字,只需按照@Nikolas 的建议使用运算符即可。
添加回答
举报