简体   繁体   English

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

[英]Sorting using Comparator Interface and java 8 Streams

Parent is a class which is inherited by Child. Parent是Child继承的类。 which is inherited by GrandChild. 这是由GrandChild继承的。 Each class contains List of the child class(ie Parent contains List of Child and Child contains List of GrandChild). 每个类都包含子类的List(即Parent包含Child和Child的List包含GrandChild的List)。 Each class contains 50 attributes(attrib1-atrib50). 每个类包含50个属性(attrib1-atrib50)。 getChildList() returns the arrayList of objects of type Child getGrandChildList() returns the arrayList of objects of type GrandChild getChildList()返回类型为Child的对象的arrayList getGrandChildList()返回GrandChild类型的对象的arrayList

Let resultSet be List of Parent 设resultSet为Parent列表

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)对resultSet进行排序,我使用此代码。

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. 现在我想根据Child类的属性1和GrandChild类的属性1对父列表进行排序。 How should I sort this. 我应该如何排序呢。

Use Comparator.comparing to make the comparators. 使用Comparator.comparing制作比较器。 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<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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM