按日期分组对象列表,并使用rxjava对它们进行排序

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

  • 2015年3月5日
    • 预订20:00
    • 预订22:00
  • 2015年3月8日
    • 预订16:00

Ada*_*m S 8

要使用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我留下的方法作为读者的练习.