【问题标题】:Sorted order in Flux of custom class自定义类的 Flux 中的排序顺序
【发布时间】:2018-06-03 08:27:25
【问题描述】:

假设我有一个类 Student,其属性为 name 和 height。

class Student{ String name; double height;}

如果我有大量学生的对象,并且我希望输出按学生姓名的升序排序,那么我该怎么做?

【问题讨论】:

    标签: reactive-programming project-reactor


    【解决方案1】:

    假设你有一个如下的学生对象数组:

    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()));
    

    【讨论】:

    • 从答案中不清楚 Student 对象的属性与什么比较?如果我想比较学生的姓氏怎么办?
    【解决方案2】:

    Accepter answer 有效,但您也可以使用方法引用,而不是滚动您自己的比较器,因为该类具有 getter:

    class Student { 
       String name; 
       double height;
    
       public String getName() {
          return name;
       }
    
       // more getters
    }
    

    你可以这样做:

    Flux.fromIterable(Arrays.asList(students)).sort(Comparator.comparing(Student::getName))
    

    【讨论】:

      【解决方案3】:

      接受answer 没问题,但我建议采用不同的方式。

      如果您有一个学生数组,那么您可以使用Arrays.sort 进行排序,然后从排序后的数组调用Flux.fromArray 创建一个 Flux。

      但如果你有一个 Flux 的学生,而不是数组,Flux 有一个操作员专门做这项工作 - Flux.collectSortedList

      Flux studentFlux = Flux.just(studentOne,studentTwo);
      studentFlux.collectSortedList((studentObj1, studentObj2) -> studentObj1.getName().compareTo(studentObj2.getName()))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-12
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多