RxJava替代sql中的group by

时间:2018-03-19 16:44:36

标签: reactive-programming java-7 rx-java2

我有Student的列表:

Observable<Student> source = Observable.fromIterable(getStudentList());

我想通过邮政编码对它们进行分组,以及它们出现的次数,但问题是我使用java 7

怎么做?

1 个答案:

答案 0 :(得分:2)

对群组本身使用groupByflatMapcount

source.groupBy(s -> s.postalCode)
.flatMapSingle(g -> 
    g.count()
    .map(v -> g.getKey() + ": " + v))
;

没有lambdas,它看起来更丑陋:

source.groupBy(new Function<Student, String>() {
    @Override public String apply(Student s) {
        return s.postalCode;
    }
})
.flatMapSingle(new Function<GroupedObservable<String, Student>, Single<String>>() {
    @Override public String apply(final GroupedObservable<String, Student> group) {
        return group.count().map(new Function<Long, String>() {
            @Override public String apply(Long count) {
                 return group.getKey() + ": " + count;
            }
        });
    }
});