RxJava alternative of group by in sql

2019-06-11 01:52发布

I have a list of Student:

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

I would like to group them by postal code, along with how many times they appear, but the problem is that I use java 7

how to do this?

1条回答
叛逆
2楼-- · 2019-06-11 02:00

Use groupBy, flatMap and count on the groups themselves:

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

Without lambdas it looks more ugly though:

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;
            }
        });
    }
});
查看更多
登录 后发表回答