使用 Java 中的 Reactive Extensions 对对象集合进行排序?

编程入门 行业动态 更新时间:2024-10-24 12:29:20
本文介绍了使用 Java 中的 Reactive Extensions 对对象集合进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用 rxjava 根据对象的一个​​或多个字段对对象集合进行排序?

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

推荐答案

Observable.toSortedList 将返回 Observable:

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.modelpareTo(car2.model); } private static Integer compareYear(Car car1, Car car2) { return Integer.valueOf(car1.yearOfProduction) pareTo(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; } }

更多推荐

使用 Java 中的 Reactive Extensions 对对象集合进行排序?

本文发布于:2023-11-06 21:34:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Java   Reactive   Extensions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!