Gio*_*gio 4 java functional-programming reactive-programming rx-java
我有一份餐馆的预订清单.我希望在一年中将它们分组,并在当天按时间排序.我怎么能用rxjava这样做?
List reservations;
class Reservation {
public String guestName;
public long time; //time in milliseconds
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT
要使用RxJava执行此操作,您可以先按时间(toSortedList
)对列表进行排序,然后在a中执行手动分组flatMap
,输出Observable<List<Reservation>>
每天给出的内容.
Observable.from(reservations)
.toSortedList(new Func2<Reservation, Reservation, Integer>() {
@Override
public Integer call(Reservation reservation, Reservation reservation2) {
return Long.compare(reservation.time, reservation2.time);
}
})
.flatMap(new Func1<List<Reservation>, Observable<List<Reservation>>>() {
@Override
public Observable<List<Reservation>> call(List<Reservation> reservations) {
List<List<Reservation>> allDays = new ArrayList<>();
List<Reservation> singleDay = new ArrayList<>();
Reservation lastReservation = null;
for (Reservation reservation : reservations) {
if (differentDays(reservation, lastReservation)) {
allDays.add(singleDay);
singleDay = new ArrayList<>();
}
singleDay.add(reservation);
lastReservation = reservation;
}
return Observable.from(allDays);
}
})
.subscribe(new Action1<List<Reservation>>() {
@Override
public void call(List<Reservation> oneDaysReservations) {
// You will get each days reservations, in order, in here to do with as you please.
}
});
Run Code Online (Sandbox Code Playgroud)
differentDays
我留下的方法作为读者的练习.
归档时间: |
|
查看次数: |
7170 次 |
最近记录: |