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