当前位置: 首页 > 面试题库 >

使用比较器接口和Java 8流进行排序

尉迟阳煦
2023-03-14
问题内容

父级是子级继承的类。由GrandChild继承。每个类都包含子类的列表(即,父类包含子类的列表,子类包含大子级的列表)。每个类包含50个属性(attrib1-atrib50)。getChildList()返回类型为Child的对象的arrayList
getGrandChildList()返回类型为GrandChild的对象的arrayList

令resultSet为父级列表

List<Parent> resultSet

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

现在,我想基于Child类的属性1和GrandChild类的属性1对父级列表进行排序。我该如何排序


问题答案:

使用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);


 类似资料:
  • 我正试图根据员工的加入日期对他们的列表进行排序。下面是我的员工类。 下面是我的比较器类:

  • 所以我正在使用一些预先存在的比较器,它们比较两个元组中的某些值,如果第一个大于第二个,则返回true,否则返回false。这是其中之一的代码: 现在,我有一个字典,里面有许多上面比较的类型的元组条目。我想以相反的顺序对它们进行排序,但我真的不知道如何完成。我在想这样的事情: 但是我不知道向比较器传递什么,因为每个比较器都有两个参数(subInfo1、subInfo2)。我不能更改比较器函数。

  • 本文向大家介绍对比Java中的Comparable排序接口和Comparator比较器接口,包括了对比Java中的Comparable排序接口和Comparator比较器接口的使用技巧和注意事项,需要的朋友参考一下 Comparable Comparable 是排序接口。 若一个类实现了Comparable接口,就意味着“该类支持排序”。 即然实现Comparable接口的类支持排序,假设现在存在

  • 当我在浏览上面的接口时,在阅读了许多相同主题的站点后,我对这些接口的语法不是很清楚。 请考虑以下代码段: 如果每个查询都是可理解的。

  • 我有一个程序可以对计算机的某个目录中的文件进行排序。我正在使用比较器接口和Collections.Sort-方法,但我无法访问调用类的输出。我也不知道如何在Sort-class中对对象进行排序。 1)如果有人能告诉我如何使用compare-method(prototyp是:sort(List List,Comparator c)我会很高兴

  • 我必须写一个程序 > 使用一个类ShopItem,其中一个项目的属性是:barCodeNumber、itemName、price和QuantityInStock。创建5个ShopItems实例(item1、item2、item3、item4和item5)的属性值为我自己的值。 为ShopItem使用一个比较器(BarcodeParator),它允许基于它们的barCodeNumber对ShopIt