首页 > 解决方案 > Sorted order in Flux of custom class

问题描述

Suppose I have a class Student with attributes name and height.

class Student{ String name; double height;}

If I have a flux of objects of students and I want to the output to be sorted in ascending order of the student's name, then how do I do that?

标签: reactive-programmingproject-reactor

解决方案


假设您有一个学生对象数组,如下所示:

Student[] students = {studentObj1, studentObj2, studentObj3};

您只需要在 Flux 提供的sort方法中使用 Comparator,它在 Java 8/反应式编程中可以写成 lambda 函数。

这里 obj1 和 obj2 是相互比较的 Student 类的对象。

obj1.compareTo(obj2) 按升序对它们进行排序。

Flux.fromIterable (Arrays.asList(students)).sort( (obj1, obj2) -> obj1.getName().compareTo(obj2.getName()));

推荐阅读