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

2022-08-31 08:43:11

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

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

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


答案 1

下面是有关对对象进行排序的教程:

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


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

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

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

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

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

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)


答案 2

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

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

或者既然列表现在有方法也像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())

现在也有静态方法,比如或者我们可以用它来轻松创建比较器,这些比较器应该比较对象中的一些特定值。Comparatorcomparing(FunctionToComparableValue)comparing(FunctionToValue, ValueComparator)

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

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

推荐