使用 Rx 运行直方图流 [英] Running histogram stream with Rx

查看:35
本文介绍了使用 Rx 运行直方图流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下单字母流

A 
B 
C 
A
D 
B 
A 
C 
D

从这个流中,我想要一个每个字母的运行计数流

And from this stream, I would like a stream of running count per letter

(A,1)
(A,1), (B,1)
(A,1), (B,1), (C,1)
(A,2), (B,1), (C,1)
(A,2), (B,1), (C,1), (D,1)
(A,2), (B,2), (C,1), (D,1)
(A,3), (B,2), (C,1), (D,1)     
(A,3), (B,2), (C,2), (D,1) 
(A,3), (B,2), (C,2), (D,2)     

,即在每个新字母处,更新和发出总数.

, i.e at each new letter, the totals are updated and emitted.

我猜这个问题与语言无关,所以请毫不犹豫地用您选择的语言提出解决方案.

I guess this problem is fairly language agnostic, so don't hesitate to propose a solution in your language of choice.

推荐答案

这是如何使用 RxJava 完成的:

This is how it can be done using RxJava:

final Observable<String> observable = Observable.just("A", "B", "C", "A", "D", "B", "A", "C", "D");
final Observable<LinkedHashMap<String, Integer>> histogram = observable.scan(new LinkedHashMap<>(), (state, value) -> {
  if (state.containsKey(value)) {
    state.put(value, state.get(value) + 1);
  } else {
    state.put(value, 1);
  }

  return state;
});

histogram.subscribe(state -> {
  System.out.println(state);
});

输出:

{}
{A=1}
{A=1, B=1}
{A=1, B=1, C=1}
{A=2, B=1, C=1}
{A=2, B=1, C=1, D=1}
{A=2, B=2, C=1, D=1}
{A=3, B=2, C=1, D=1}
{A=3, B=2, C=2, D=1}
{A=3, B=2, C=2, D=2}

这篇关于使用 Rx 运行直方图流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆