我希望为我的通讯录应用程序实现排序功能。
我想要对一个ArrayList<Contact> contactArray
进行排序。其中Contact
是一个包含四个字段的类:姓名、家庭号码、移动电话和地址。我想按照姓名
排序。
我该如何编写自定义排序函数来实现这一点?
我希望为我的通讯录应用程序实现排序功能。
我想要对一个ArrayList<Contact> contactArray
进行排序。其中Contact
是一个包含四个字段的类:姓名、家庭号码、移动电话和地址。我想按照姓名
排序。
我该如何编写自定义排序函数来实现这一点?
以下是一个关于对象排序的教程:
虽然我会给出一些例子,但我还是建议你去阅读这个教程。
有各种各样的方法可以对 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"));
(从代码中可以看出,可能为空的字段已经被包含在内,以避免在排序过程中出现空指针异常)
除了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)
,因此它是功能接口。
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());
});
(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).
这个页面告诉你如何对集合进行排序,例如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;
}
...
}
}
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);
}
}
sort(contacts, on(Contact.class).getName());
或通过它们的地址:
sort(contacts, on(Contacts.class).getAddress());
等等。更一般地说,它提供了一个DSL来访问和操作您的集合,以许多方式,如基于某些条件过滤或分组您的联系人,聚合一些属性值等。
好的,我知道这个问题很久以前就被回答了...但是,这里有一些新信息:
假设所讨论的Contact类已经通过实现Comparable定义了自然排序,但是你想要覆盖那个排序,比如按名称排序。下面是现代的做法:
List<Contact> contacts = ...;
contacts.sort(Comparator.comparing(Contact::getName).reversed().thenComparing(Comparator.naturalOrder());
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);
}
}
}
}
}
Collections.sort是一个很好的排序实现。如果您没有为Contact实现Comparable接口,您需要传入一个Comparator实现。
值得注意的是:
排序算法是修改后的归并排序(如果低子列表中的最高元素小于高子列表中的最低元素,则省略合并)。此算法提供了保证的n log(n)性能。指定的列表必须是可修改的,但不需要是可调整大小的。此实现将指定的列表转储到数组中,对数组进行排序,并迭代列表,从数组中相应位置重置每个元素。这避免了尝试原地排序链表导致的n2 log(n)性能问题。
归并排序可能比大多数搜索算法更好。
static
的,或者也许是final
的... 或者类似这样的东西。 - Stobor(o1 == null && o2 == null) ? 0 :
吗?) - Stobor