使用比较器接口和 java 8 流进行排序
Sorting using Comparator Interface and java 8 Streams
Parent 是 class,由 Child 继承。由 GrandChild 继承。每个 class 包含子项列表 class(即父项包含子项列表,子项包含孙子项列表)。每个 class 包含 50 个属性(attrib1-atrib50)。
getChildList() returns Child 类型对象的数组列表 getGrandChildList() returns GrandChild
类型对象的数组列表
设 resultSet 为 Parent 列表
List<Parent> resultSet
现在我想根据一些属性对列表进行排序。例如,如果我想根据两个父属性(比如属性 1 和属性 2)对结果集进行排序,我使用此代码。
Comparator<Parent> byFirst = (e1, e2) -> e2.getAttrib1().compareTo(e1.getAttrib1());
Comparator<Parent> bySecond = (e1, e2) -> e1.getAttrib2().compareTo(e2.getAttrib2());
Comparator<Parent> byThird = byFirst.thenComparing(bySecond);
List<Parent> sortedList = resultSet.stream().sorted(byThird).collect(Collectors.toList());
现在我想根据 Child class 的属性 1 和 GrandChild class 的属性 1 对 parentlist 进行排序。我该如何排序。
使用Comparator.comparing
制作比较器。只要弄清楚你想比较什么。它看起来像这样,除了你将编写任何你想用来提取要比较的值的逻辑:
Comparator<Parent> byAttr1ofFirstChild = Comparator.comparing(
parent -> parent.getChildren().get(0).getAttr1()
);
Comparator<Parent> byAttr1ofFirstGrandChild = Comparator.comparing(
parent -> parent.getChildren().get(0).getGrandChildren().get(0).getAttr1()
);
List<Parent> sortedList = parents.stream()
.sorted(byAttr1ofFirstChild.thenComparing(byAttr1ofFirstGrandChild))
.collect(toList());
Comparator.comparing
也会使您问题中的示例更好(使用静态导入):
Comparator<Parent> byFirst = comparing(Parent::getAttrib1, reverseOrder());
Comparator<Parent> bySecond = comparing(Parent::getAttrib2);
Parent 是 class,由 Child 继承。由 GrandChild 继承。每个 class 包含子项列表 class(即父项包含子项列表,子项包含孙子项列表)。每个 class 包含 50 个属性(attrib1-atrib50)。 getChildList() returns Child 类型对象的数组列表 getGrandChildList() returns GrandChild
类型对象的数组列表设 resultSet 为 Parent 列表
List<Parent> resultSet
现在我想根据一些属性对列表进行排序。例如,如果我想根据两个父属性(比如属性 1 和属性 2)对结果集进行排序,我使用此代码。
Comparator<Parent> byFirst = (e1, e2) -> e2.getAttrib1().compareTo(e1.getAttrib1());
Comparator<Parent> bySecond = (e1, e2) -> e1.getAttrib2().compareTo(e2.getAttrib2());
Comparator<Parent> byThird = byFirst.thenComparing(bySecond);
List<Parent> sortedList = resultSet.stream().sorted(byThird).collect(Collectors.toList());
现在我想根据 Child class 的属性 1 和 GrandChild class 的属性 1 对 parentlist 进行排序。我该如何排序。
使用Comparator.comparing
制作比较器。只要弄清楚你想比较什么。它看起来像这样,除了你将编写任何你想用来提取要比较的值的逻辑:
Comparator<Parent> byAttr1ofFirstChild = Comparator.comparing(
parent -> parent.getChildren().get(0).getAttr1()
);
Comparator<Parent> byAttr1ofFirstGrandChild = Comparator.comparing(
parent -> parent.getChildren().get(0).getGrandChildren().get(0).getAttr1()
);
List<Parent> sortedList = parents.stream()
.sorted(byAttr1ofFirstChild.thenComparing(byAttr1ofFirstGrandChild))
.collect(toList());
Comparator.comparing
也会使您问题中的示例更好(使用静态导入):
Comparator<Parent> byFirst = comparing(Parent::getAttrib1, reverseOrder());
Comparator<Parent> bySecond = comparing(Parent::getAttrib2);