为了账号安全,请及时绑定邮箱和手机立即绑定

使用自定义排序顺序对象的数组列表进行排序

使用自定义排序顺序对象的数组列表进行排序

qq_花开花谢_0 2019-06-14 15:17:56
使用自定义排序顺序对象的数组列表进行排序我正在为我的地址簿应用程序实现一个排序功能。我想整理一下ArrayList<Contact> contactArray. Contact是一个包含四个字段的类:名称、家庭号码、移动电话和地址。我想整理一下name.如何编写自定义排序函数来完成此操作?
查看完整描述

3 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

除了已经发布的内容之外,您还应该知道,从Java 8开始,我们可以缩短代码并编写如下:

Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));

或者因为现在的列表sort方法

yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));

说明:

从Java 8开始,函数接口(只有一个抽象方法的接口-它们可以有更多的默认或静态方法)可以很容易地使用以下方法实现:

Comparator<T>只有一个抽象方法int compare(T o1, T o2)它是功能接口。

所以,而不是(例如)@BalusC 回答)

Collections.sort(contacts, new Comparator<Contact>() {
    public int compare(Contact one, Contact other) {
        return one.getAddress().compareTo(other.getAddress());
    }});

我们可以将此代码简化为:

Collections.sort(contacts, (Contact one, Contact other) -> {
     return one.getAddress().compareTo(other.getAddress());});

我们可以通过跳过来简化这个(或任何)lambda。

  • 参数类型(Java将根据方法签名推断它们)
  • {return ... }

所以而不是

(Contact one, Contact other) -> {
     return one.getAddress().compareTo(other.getAddress();}

我们可以写

(one, other) -> one.getAddress().compareTo(other.getAddress())

现在也是Comparator有类似的静态方法comparing(FunctionToComparableValue)comparing(FunctionToValue, ValueComparator)我们可以用它轻松地创建比较器,它应该比较来自对象的一些特定值。

换句话说,我们可以将上面的代码重写为

Collections.sort(contacts, Comparator.comparing(Contact::getAddress)); //assuming that Address implements Comparable (provides default order).


查看完整回答
反对 回复 2019-06-14
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

本页告诉您有关排序集合(如ArrayList)的所有需要了解的信息。

基本上你需要

  • 使你

    Contact

    类实现

    Comparable

    界面
    • 创建方法

      public int compareTo(Contact anotherContact)

      在里面。
  • 一旦你这么做了,你就可以打电话

    Collections.sort(myContactList);,

    • 哪里

      myContactList

      ArrayList<Contact>

      (或任何其他收集

      Contact).

还有另一种方法,包括创建一个比较器类,您也可以从链接的页面中了解到这一点。

例子:

public class Contact implements Comparable<Contact> {

    ....

    //return -1 for less than, 0 for equals, and 1 for more than
    public compareTo(Contact anotherContact) {
        int result = 0;
        result = getName().compareTo(anotherContact.getName());
        if (result != 0)
        {
            return result;
        }
        result = getNunmber().compareTo(anotherContact.getNumber());
        if (result != 0)
        {
            return result;
        }
        ...
    }}


查看完整回答
反对 回复 2019-06-14
  • 3 回答
  • 0 关注
  • 646 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号