Sort collection of objects with Reactive Extensions in Java?

断了今生、忘了曾经 提交于 2019-12-25 02:06:34

问题


How can I can sort a collection of objects using rxjava based on one or more fields of the objects?

public class Car {

   public String model;
   public int numberOfWheels;
   public String color;
   public int yearOfProduction;

}

List<Car> cars = new ArrayList<>();
cars.add(...);
cars.add(...);

Observable<List<Car>> getCars() { Observable.just(cars) };

Observable<List<Car>> getCarsSortedByModel() { ??? };

Observable<List<Car>> getCarsSortedByColor() { ??? };

Observable<List<Car>> getCarsSortedByModelAndColor() { ??? };


回答1:


Observable.toSortedList will return Observable<List<Car>>:

public class Car {
  public String model;
  public int numberOfWheels;
  public String color;
  public int yearOfProduction;

  public static void main(String[] args) {
    cars()
       .toSortedList(Car::compareModel)
       .subscribe(System.out::println) ;

    cars()
       .toSortedList(Car::compareYear)
       .subscribe(System.out::println) ;

  }

  private static Integer compareModel(Car car1, Car car2) {
    return car1.model.compareTo(car2.model);
  }

  private static Integer compareYear(Car car1, Car car2) {
    return Integer.valueOf(car1.yearOfProduction)
            .compareTo(car2.yearOfProduction);
  }

  private static Observable<Car> cars(){
    Car car1 = new Car();
    car1.model = "robin";
    car1.color = "red";
    car1.numberOfWheels = 3;
    car1.yearOfProduction = 1972;
    Car car2 = new Car();
    car2.model = "corolla";
    car2.color = "white";
    car2.numberOfWheels = 4;
    car2.yearOfProduction = 1992;
    return Observable.just(car1, car2);
  }

  public String toString(){
    return model;
  }
}


来源:https://stackoverflow.com/questions/29565447/sort-collection-of-objects-with-reactive-extensions-in-java

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