RxJava alternative of group by in sql

你说的曾经没有我的故事 提交于 2019-12-08 09:07:28

问题


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:


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;
            }
        });
    }
});


来源:https://stackoverflow.com/questions/49368164/rxjava-alternative-of-group-by-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!