使用Comparator接口和java 8 Streams进行排序 [英] Sorting using Comparator Interface and java 8 Streams

查看:777
本文介绍了使用Comparator接口和java 8 Streams进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

让resultSet为Parent的列表

Let resultSet be List of Parent

List<Parent> resultSet

现在我想根据一些属性对列表进行排序。例如,如果我想根据两个父属性(比如属性1和属性2)对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.

    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类的属性1和GrandChild类的属性1对父列表进行排序。我应该如何排序。

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.

推荐答案

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

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<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.comparing would also make the examples in your question much nicer (using static imports) :

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

这篇关于使用Comparator接口和java 8 Streams进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆