Sam*_*ra0 114 java sorting collections arraylist
我希望为我的地址簿应用程序实现一个排序功能.
我想要排序ArrayList<Contact> contactArray
.Contact
是一个包含四个字段的类:姓名,家庭电话号码,手机号码和地址.我想要排序name
.
如何编写自定义排序功能来执行此操作?
Bal*_*usC 264
这是一个关于订购对象的教程:
虽然我会给出一些例子,但我仍然建议你阅读它.
排序有多种方式ArrayList
.如果要定义自然(默认)排序,则需要Contact
实现Comparable
.假设你想默认排序name
,那么do(为简单起见省略了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.
}
Run Code Online (Sandbox Code Playgroud)
这样你就可以做到
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.
Collections.sort(contacts);
Run Code Online (Sandbox Code Playgroud)
如果要定义外部可控排序(它会覆盖自然排序),那么您需要创建一个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());
}
});
Run Code Online (Sandbox Code Playgroud)
您甚至可以Comparator
在Contact
自身中定义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);
}
};
}
Run Code Online (Sandbox Code Playgroud)
可以使用如下:
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);
Run Code Online (Sandbox Code Playgroud)
最重要的是,您可以考虑使用通用的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));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用如下:
// Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new BeanComparator("phone"));
Run Code Online (Sandbox Code Playgroud)
(正如您在代码中看到的那样,在排序过程中可能已经覆盖了空字段以避免NPE)
Psh*_*emo 25
除了已发布的内容之外,您应该知道自Java 8以来我们可以缩短代码并将其编写为:
Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
Run Code Online (Sandbox Code Playgroud)
或者因为List现在有sort
方法
yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
Run Code Online (Sandbox Code Playgroud)
从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());
}
});
Run Code Online (Sandbox Code Playgroud)
我们可以将此代码减少为:
Collections.sort(contacts, (Contact one, Contact other) -> {
return one.getAddress().compareTo(other.getAddress());
});
Run Code Online (Sandbox Code Playgroud)
我们可以通过跳过来简化这个(或任何)lambda
{return
......}
而不是
(Contact one, Contact other) -> {
return one.getAddress().compareTo(other.getAddress();
}
Run Code Online (Sandbox Code Playgroud)
我们可以写
(one, other) -> one.getAddress().compareTo(other.getAddress())
Run Code Online (Sandbox Code Playgroud)
现在Comparator
也有静态方法,comparing(FunctionToComparableValue)
或者comparing(FunctionToValue, ValueComparator)
我们可以使用它来轻松创建比较器,它们应该比较来自对象的一些特定值.
换句话说,我们可以将上面的代码重写为
Collections.sort(contacts, Comparator.comparing(Contact::getAddress));
//assuming that Address implements Comparable (provides default order).
Run Code Online (Sandbox Code Playgroud)
此页面告诉您有关排序集合的所有信息,例如ArrayList.
基本上你需要
Contact
类实现Comparable
接口
public int compareTo(Contact anotherContact)
在其中创建方法.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;
}
...
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
168271 次 |
最近记录: |