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

131

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

我想要对一个ArrayList<Contact> contactArray进行排序。其中Contact是一个包含四个字段的类:姓名、家庭号码、移动电话和地址。我想按照姓名排序。

我该如何编写自定义排序函数来实现这一点?

12个回答

278

以下是一个关于对象排序的教程:

虽然我会给出一些例子,但我还是建议你去阅读这个教程。


有各种各样的方法可以对 ArrayList 进行排序。如果你想定义一个自然(默认)排序,那么你需要让 Contact 实现 Comparable 接口。假设你想按照默认的 name 进行排序,那么可以这样做(为简单起见,省略了 null 检查):

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,这样你就可以重复使用它们,而不是每次重新创建:

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

(从代码中可以看出,可能为空的字段已经被包含在内,以避免在排序过程中出现空指针异常)


2
我会添加预定义多个比较器的可能性,然后通过名称使用它们... - Stobor
2
事实上,我刚刚做到了。比试图解释自己要容易得多。 - Stobor
1
那些比较器定义可能也应该是 static 的,或者也许是 final 的... 或者类似这样的东西。 - Stobor
1
呵呵呵……BeanComparator就像棒棒的一样!:-)(我不记得空值比较的确切逻辑是什么了,但在这个返回行的开头需要一个(o1 == null && o2 == null) ? 0 :吗?) - Stobor
我读过的最好的答案之一。当我实现关于Comparable的前半部分时,我突然想知道如果我想按多个搜索进行搜索怎么办,然后在下面的5行中,这个问题也得到了回答... - WORMSS
显示剩余8条评论

31

除了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).

8

这个页面告诉你如何对集合进行排序,例如ArrayList。

基本上你需要:

  • 让你的Contact类实现Comparable接口
    • 在其中创建一个方法public int compareTo(Contact anotherContact)
  • 一旦你这样做了,你只需要调用Collections.sort(myContactList);
    • 其中myContactListArrayList<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;
        }
        ...
    }
}

5

BalusC和bguiz已经详细回答了如何使用Java内置的比较器。

我只想补充一点,Google Collections有一个Ordering类,比标准比较器更加“强大”。 它可能值得一试。您可以做一些很酷的事情,例如组合排序,反转排序,根据函数结果对对象进行排序...

这里是一篇博客文章,提到了一些它的好处。


请注意,google-collections现在是Guava(Google的通用Java库)的一部分,因此如果您想使用Ordering类,则可能需要依赖于Guava(或Guava的集合模块)。 - Etienne Neveu

4
你需要让你的Contact类实现Comparable,然后实现compareTo(Contact)方法。这样,Collections.sort就能帮你排序了。根据我提供的页面,compareTo会“返回负整数、零或正整数,表示此对象小于、等于或大于指定对象”。例如,如果你想按名称(A到Z)排序,你的类应该像这样:
public class Contact implements Comparable<Contact> {

    private String name;

    // all the other attributes and methods

    public compareTo(Contact other) {
        return this.name.compareTo(other.name);
    }
}

与我合作得很好,谢谢!我还使用了compareToIgnoreCase来忽略大小写。 - Rani Kheir

3
通过使用 lambdaj,您可以按照以下方式对联系人集合进行排序(例如按姓名)
sort(contacts, on(Contact.class).getName());

或通过它们的地址:

sort(contacts, on(Contacts.class).getAddress());

等等。更一般地说,它提供了一个DSL来访问和操作您的集合,以许多方式,如基于某些条件过滤或分组您的联系人,聚合一些属性值等。


1

好的,我知道这个问题很久以前就被回答了...但是,这里有一些新信息:

假设所讨论的Contact类已经通过实现Comparable定义了自然排序,但是你想要覆盖那个排序,比如按名称排序。下面是现代的做法:

List<Contact> contacts = ...;

contacts.sort(Comparator.comparing(Contact::getName).reversed().thenComparing(Comparator.naturalOrder());

这样它将首先按名称排序(倒序),然后对于名称冲突,它将回退到Contact类本身实现的“自然”顺序。

0
我是按照以下方式完成的。 number和name是两个ArrayList。我必须对name进行排序。如果name ArrayList发生任何更改,则number ArrayList的顺序也会改变。
public void sortval(){

        String tempname="",tempnum="";

         if (name.size()>1) // check if the number of orders is larger than 1
            {
                for (int x=0; x<name.size(); x++) // bubble sort outer loop
                {
                    for (int i=0; i < name.size()-x-1; i++) {
                        if (name.get(i).compareTo(name.get(i+1)) > 0)
                        {

                            tempname = name.get(i);

                            tempnum=number.get(i);


                           name.set(i,name.get(i+1) );
                           name.set(i+1, tempname);

                            number.set(i,number.get(i+1) );
                            number.set(i+1, tempnum);


                        }
                    }
                }
            }



}

你会花更长的时间来编写代码,性能排序不够优化,出现更多错误(但希望测试更多),而且代码将更难传递给其他人。所以这不是正确的方法。它可能能够运行,但这并不意味着它是正确的。 - Eric Rini

0
你应该使用Arrays.sort函数。包含的类应该实现Comparable接口。

问题在于 OP 使用的是 ArrayList,而不是数组。 - Pshemo

0

Collections.sort是一个很好的排序实现。如果您没有为Contact实现Comparable接口,您需要传入一个Comparator实现

值得注意的是:

排序算法是修改后的归并排序(如果低子列表中的最高元素小于高子列表中的最低元素,则省略合并)。此算法提供了保证的n log(n)性能。指定的列表必须是可修改的,但不需要是可调整大小的。此实现将指定的列表转储到数组中,对数组进行排序,并迭代列表,从数组中相应位置重置每个元素。这避免了尝试原地排序链表导致的n2 log(n)性能问题。

归并排序可能比大多数搜索算法更好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接