使用比较器接口和 java 8 Streams 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29964108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting using Comparator Interface and java 8 Streams
提问by Manu Joy
Parent is a class which is inherited by Child. which is inherited by GrandChild. Each class contains List of the child class(i.e Parent contains List of Child and Child contains List of GrandChild). Each class contains 50 attributes(attrib1-atrib50). getChildList() returns the arrayList of objects of type Child getGrandChildList() returns the arrayList of objects of type GrandChild
Parent 是一个由 Child 继承的类。由 GrandChild 继承。每个类都包含子类的列表(即父类包含子类的列表,子类包含孙子的列表)。每个类包含 50 个属性(attrib1-atrib50)。getChildList() 返回 Child 类型对象的 arrayList getGrandChildList() 返回 GrandChild 类型对象的 arrayList
Let resultSet be List of Parent
让 resultSet 成为父列表
List<Parent> resultSet
Now I want to sort the list based on some attributes. For example if I want to sort resultSet based on two parent attributes(say Attribute 1 and attribute 2, I use this code.
现在我想根据一些属性对列表进行排序。例如,如果我想根据两个父属性(比如属性 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());
Now I want to sort the parentlist based on attribute 1 of Child class and attribute 1 of GrandChild class. How should I sort this.
现在我想根据 Child 类的属性 1 和 GrandChild 类的属性 1 对 parentlist 进行排序。我该如何排序。
采纳答案by Misha
Use Comparator.comparing
to make the comparators. Just figure out what you want to compare. It will looks something like this, except you will write whatever logic you want to use to extract the values to compare:
使用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
would also make the examples in your question much nicer (using static imports) :
Comparator.comparing
也会使您的问题中的示例更好(使用静态导入):
Comparator<Parent> byFirst = comparing(Parent::getAttrib1, reverseOrder());
Comparator<Parent> bySecond = comparing(Parent::getAttrib2);