自定义 Flux 中的排序顺序 class
Sorted order in Flux of custom class
假设我有一个 class 具有属性名称和身高的学生。
class Student{ String name; double height;}
如果我有大量的学生对象,并且我希望输出按学生姓名的升序排序,那么我该怎么做?
假设您有一个学生对象数组,如下所示:
Student[] students = {studentObj1, studentObj2, studentObj3};
你只需要使用Comparator,在Java8/反应式编程中可以写成lambda函数,在Flux提供的sort方法中
这里obj1和obj2是Studentclass的对象,它们相互比较。
obj1.compareTo(obj2) 按升序对它们进行排序。
Flux.fromIterable (Arrays.asList(students)).sort( (obj1, obj2) -> obj1.getName().compareTo(obj2.getName()));
已接受 可以,但我建议采用不同的方式。
如果你有一个学生数组,那么你可以使用 Arrays.sort and then create a Flux from the sorted array calling Flux.fromArray.
进行排序
但是如果你有一个 student 的 Flux,而不是数组,Flux 有一个运算符来专门完成这项工作 - Flux.collectSortedList
Flux studentFlux = Flux.just(studentOne,studentTwo);
studentFlux.collectSortedList((studentObj1, studentObj2) -> studentObj1.getName().compareTo(studentObj2.getName()))
Accepter 有效,但如果 class 有吸气剂,您还可以使用方法引用,而不是滚动您自己的比较器:
class Student {
String name;
double height;
public String getName() {
return name;
}
// more getters
}
然后你可以这样做:
Flux.fromIterable(Arrays.asList(students)).sort(Comparator.comparing(Student::getName))
假设我有一个 class 具有属性名称和身高的学生。
class Student{ String name; double height;}
如果我有大量的学生对象,并且我希望输出按学生姓名的升序排序,那么我该怎么做?
假设您有一个学生对象数组,如下所示:
Student[] students = {studentObj1, studentObj2, studentObj3};
你只需要使用Comparator,在Java8/反应式编程中可以写成lambda函数,在Flux提供的sort方法中
这里obj1和obj2是Studentclass的对象,它们相互比较。
obj1.compareTo(obj2) 按升序对它们进行排序。
Flux.fromIterable (Arrays.asList(students)).sort( (obj1, obj2) -> obj1.getName().compareTo(obj2.getName()));
已接受
如果你有一个学生数组,那么你可以使用 Arrays.sort and then create a Flux from the sorted array calling Flux.fromArray.
进行排序但是如果你有一个 student 的 Flux,而不是数组,Flux 有一个运算符来专门完成这项工作 - Flux.collectSortedList
Flux studentFlux = Flux.just(studentOne,studentTwo);
studentFlux.collectSortedList((studentObj1, studentObj2) -> studentObj1.getName().compareTo(studentObj2.getName()))
Accepter
class Student {
String name;
double height;
public String getName() {
return name;
}
// more getters
}
然后你可以这样做:
Flux.fromIterable(Arrays.asList(students)).sort(Comparator.comparing(Student::getName))