java8 comparator接口,使用Comparator接口和java 8 Streams进行排序
发布日期:2022-02-18 13:20:03 浏览次数:8 分类:技术文章

本文共 1842 字,大约阅读时间需要 6 分钟。

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

Let resultSet be List of Parent

List 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 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());

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.

解决方案

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

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

Comparator bySecond = comparing(Parent::getAttrib2);

转载地址:https://blog.csdn.net/weixin_28926205/article/details/118827162 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:计算机学校位置阜阳,计算机学校附近学校
下一篇:指令格式实验计算机组成原理,计算机组成原理实验第五讲.ppt

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年03月28日 21时43分14秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章