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

本文介绍了如何在Java中对ArrayList中的对象进行排序。可以通过让对象实现Comparable接口来设定自然排序,或者使用Comparator来定义外部可控排序。此外,还提供了通用的BeanComparator用于比较javabean的不同字段,例如Contact的phone和address字段。
摘要由CSDN通过智能技术生成

小编典典

这是有关订购对象的教程:

Java教程-集合-对象排序

尽管我会举一些例子,但我还是建议你阅读它。

有多种排序方式ArrayList。如果要定义自然的(默认)排序,则需要让ContactImplement实现Comparable。假设你想默认在上进行排序name,然后执行(为简单起见,省略了nullchecks):

public class Contact implements Comparable {

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 contacts = new ArrayList();

// Fill it.

Collections.sort(contacts);

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

List contacts = new ArrayList();

// Fill it.

// Now sort by address instead of name (default).

Collections.sort(contacts, new Comparator() {

public int compare(Contact one, Contact other) {

return one.getAddress().compareTo(other.getAddress());

}

});

你甚至可以Comparator在Contact自身中定义,以便你可以重用它们,而不必每次都重新创建它们:

public class Contact {

private String name;

private String phone;

private Address address;

// ...

public static Comparator COMPARE_BY_PHONE = new Comparator() {

public int compare(Contact one, Contact other) {

return one.phone.compareTo(other.phone);

}

};

public static Comparator COMPARE_BY_ADDRESS = new Comparator() {

public int compare(Contact one, Contact other) {

return one.address.compareTo(other.address);

}

};

}

可以如下使用:

List contacts = new ArrayList();

// 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 {

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) o1).compareTo(o2));

}

}

你可以使用以下方法:

// Sort on "phone" field of the Contact bean.

Collections.sort(contacts, new BeanComparator("phone"));

(如你在代码中所见,可能的空字段已经被覆盖以避免在排序过程中出现NPE)

2020-02-26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值