问题

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

我想排序anArrayList<Contact> contactArray.Contact是一个包含四个字段的类:名称,家庭电话号码,手机号码和地址。我想排序name

如何编写自定义排序功能来执行此操作?


#1 热门回答(255 赞)

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

  • Java教程 - 集合 - 对象排序

虽然我会给出一些例子,但我仍然建议你阅读它。

有多种方法可以对ArrayList进行排序。如果你想定义a自然(默认)订购,那么你需要letContactimplementComparable。假设你想在name上默认排序,那么为了简单起见省略了nullchecks:

public class Contact implements Comparable<Contact> {

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

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

如果要定义a外部可控订购(它会覆盖自然顺序),则需要创建aComparator

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中定义Comparators,以便你可以重复使用它们而不是每次都重新创建它们:

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

为了使顶部关闭,你可以考虑使用a通用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)


#2 热门回答(20 赞)

除了已发布的内容之外,你应该知道,自Java 8起,我们可以缩短代码并将其编写为:

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

或者因为List现在有sort方法

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

###说明:

从Java 8开始,功能接口(只有一个抽象方法的接口 - 它们可以有更多的默认或静态方法)可以使用以下方法轻松实现:

  • lambdas参数 - > body
  • 或方法引用source :: method。

由于Comparator<T>只有一个抽象方法int compare(T o1, T o2)是功能界面。

而不是(例如来自@BalusCanswer)

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将根据方法签名推断它们)

而不是

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

我们可以写

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

另外现在Comparator有静态方法,如comparing(FunctionToComparableValue)或667331971,我们可以使用它来轻松创建比较器,它们应该比较对象的某些特定值。

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

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

#3 热门回答(8 赞)

This page会告诉你有关排序集合的所有信息,例如ArrayList。

基本上你需要

  • 通过在其中创建方法public int compareTo(Contact anotherContact),使你的Contact类实现Comparable接口。
  • 执行此操作后,你可以调用Collections.sort(myContactList);,其中myContactList是ArrayList <Contact>(或任何其他Contact集合)。

还有另一种方法,包括创建一个Comparator类,你也可以从链接页面中读到它。

例:

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;
        }
        ...
    }
}

原文链接