我有一份餐馆名单'保留。 我希望在一年中将它们分组,并在当天按时间排序。 我怎么能用rxjava这样做?
List reservations;
class Reservation {
public String guestName;
public long time; //time in milliseconds
}
输出
答案 0 :(得分:8)
要使用RxJava执行此操作,您可以先按时间(toSortedList
)对列表进行排序,然后在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.
}
});
我留下的differentDays
方法作为读者练习。
答案 1 :(得分:4)
由于您已经拥有完整的预订列表(即List<Reservation>
,而不是Observable<Reservation>
),因此您不需要RxJava - 您可以使用Java 8 stream /集合API:
Map<Calendar, List<Reservation>> grouped = reservations
.stream()
.collect(Collectors.groupingBy(x -> {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(x.time);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}));
正如您所看到的,每年的所有工作都是groupingBy
。如果您的初始数据使用Calendar
而不是long
作为时间戳,那么这看起来会更简单,例如:
Map<Calendar, List<Reservation>> grouped = reservations
.stream()
.collect(Collectors.groupingBy(x -> x.time.get(Calendar.DAY_OF_YEAR)));