使用自定义排序顺序对对象的 ArrayList 进行排序

新手上路,请多包涵

我希望为我的地址簿应用程序实现排序功能。

我想对 ArrayList<Contact> contactArray 进行排序。 Contact 是一个包含四个字段的类:姓名,家庭号码,手机号码和地址。我想排序 name

如何编写自定义排序函数来做到这一点?

原文由 Sameera0 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 684
2 个回答

这是关于订购对象的教程:

虽然我会举一些例子,但我还是建议阅读它。


有多种方法可以对 ArrayList 进行排序。如果要定义 自然(默认) 排序,则需要让 Contact 实现 Comparable 。假设您想默认排序 name ,然后执行(为简单起见省略了空检查):

 public class Contact implements Comparable<Contact> {

    private String name;
    private String phone;
    private Address address;

    @Override
    public int compareTo(Contact other) {
        return name.compareTo(other.name);
    }

    // Add/generate getters/setters and other boilerplate.
}

这样你就可以做到

List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

Collections.sort(contacts);


如果要定义 外部可控排序(覆盖自然排序),则需要创建一个 Comparator

 List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Now sort by address instead of name (default).
Collections.sort(contacts, new Comparator<Contact>() {
    public int compare(Contact one, Contact other) {
        return one.getAddress().compareTo(other.getAddress());
    }
});


您甚至可以在 Contact 本身中定义 Comparator s,以便您可以重用它们而不是每次都重新创建它们:

 public class Contact {

    private String name;
    private String phone;
    private Address address;

    // ...

    public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.phone.compareTo(other.phone);
        }
    };

    public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.address.compareTo(other.address);
        }
    };

}

可以按如下方式使用:

 List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Sort by address.
Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);

// Sort later by phone.
Collections.sort(contacts, Contact.COMPARE_BY_PHONE);


为了达到顶峰,您可以考虑使用 通用的 javabean 比较器

 public class BeanComparator implements Comparator<Object> {

    private String getter;

    public BeanComparator(String field) {
        this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
    }

    public int compare(Object o1, Object o2) {
        try {
            if (o1 != null && o2 != null) {
                o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
                o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
            }
        } catch (Exception e) {
            // If this exception occurs, then it is usually a fault of the developer.
            throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
        }

        return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2));
    }

}

您可以按如下方式使用:

 // Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new BeanComparator("phone"));

(正如您在代码中看到的,可能已经覆盖了空字段以避免在排序期间出现 NPE)

原文由 BalusC 发布,翻译遵循 CC BY-SA 4.0 许可协议

除了 BalusC 已经发布的内容 之外,值得指出的是,自 Java 8 以来,我们可以缩短代码并将其编写为:

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

或者因为 List 现在有 sort 方法也喜欢

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

解释:

从 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).

原文由 Pshemo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题