使用Comparator接口和java 8 Streams进行排序

Parent是Childinheritance的类。 这是GrandChildinheritance的。 每个类都包含子类的List(即Parent包含Child和Child的List包含GrandChild的List)。 每个类包含50个属性(attrib1-atrib50)。 getChildList()返回类型为Child的对象的arrayList getGrandChildList()返回类型为GrandChild的对象的arrayList

设resultSet为Parent列表

List resultSet 

现在我想根据一些属性对列表进行排序。 例如,如果我想基于两个父属性(比如属性1和属性2)对resultSet进行排序,我使用此代码。

  Comparator byFirst = (e1, e2) -> e2.getAttrib1().compareTo(e1.getAttrib1()); Comparator bySecond = (e1, e2) -> e1.getAttrib2().compareTo(e2.getAttrib2()); Comparator byThird = byFirst.thenComparing(bySecond); List sortedList = resultSet.stream().sorted(byThird) .collect(Collectors.toList()); 

现在我想根据Child类的属性1和GrandChild类的属性1对父列表进行排序。 我应该如何排序呢。

使用Comparator.comparing制作比较器。 找出你想要比较的东西。 它看起来像这样,除了你将编写你想要用来提取要比较的值的任何逻辑:

 Comparator byAttr1ofFirstChild = Comparator.comparing( parent -> parent.getChildren().get(0).getAttr1() ); Comparator byAttr1ofFirstGrandChild = Comparator.comparing( parent -> parent.getChildren().get(0).getGrandChildren().get(0).getAttr1() ); List sortedList = parents.stream() .sorted(byAttr1ofFirstChild.thenComparing(byAttr1ofFirstGrandChild)) .collect(toList()); 

Comparator.comparing还可以使您的问题中的示例更好(使用静态导入):

 Comparator byFirst = comparing(Parent::getAttrib1, reverseOrder()); Comparator bySecond = comparing(Parent::getAttrib2);