排序对列表物体采用一个自定义的排列顺序
-
06-07-2019 - |
题
我找到实现的一种特征对于我的地址簿应用程序。
我想要一个排序 ArrayList<Contact> contactArray
. Contact
是一类,其中包含四个领域:姓名、家庭数量,手机号码和地址。我想上的排序 name
.
我怎么可以写一个自定义的排序功能做到这一点?
解决方案
这一教程有关订购的对象:
虽然我将给出一些例子,我会推荐读它呢。
有各种不同的方式进行排序 ArrayList
.如果你想定义 自然的 (默认) 订购, 然后你需要我们 Contact
实施 Comparable
.假设你要排序上默认 name
, 然后做(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.
}
这样你就可以做
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());
}
});
你甚至可以定义 Comparator
s在 Contact
本身所以你可以重复使用他们,而不是重建他们每次:
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"));
(正如你看到的在代码,可能空领域已经涵盖了以避免在展会上,就在排序)
其他提示
除了已经张贴你应该知道,由于Java8我们可以缩短我们的代码和编写这样的:
Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
或是因为名单现在已 sort
方法
yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
说明:
由于Java8、功能性的接口(接口只有一个抽象的方法-他们可以有更多的默认或静态的方法)可以很容易地实现使用:
由于 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());
});
我们可以简化这个(或)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).
这页 告诉你所有你需要知道关于分类集,例如对列表.
基本上,你需要
- 让你的
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;
}
...
}
}
您需要使您的联系人类实现 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);
}
}
通过使用 lambdaj 你可以排序的集合你的联系人(例如通过他们的名字)如下
sort(contacts, on(Contact.class).getName());
或者通过他们的地址:
sort(contacts, on(Contacts.class).getAddress());
等等。更一般来说,它提供了一个DSL的访问和操作系列在许多方面,就像过滤或分组的联系人基于某些条件下,汇总他们的一些财产价值等。
Collections.sort是一个很好的排序实现。如果您没有为Contact实现可比较的,则需要传入比较器实现
值得注意的是:
排序算法是修改后的mergesort(如果低子列表中的最高元素小于高子列表中的最低元素,则省略合并)。该算法提供有保证的n log(n)性能。指定的列表必须是可修改的,但无需调整大小。此实现将指定的列表转储到数组中,对数组进行排序,并迭代列表,从数组中的相应位置重置每个元素。这样可以避免尝试对链接列表进行排序所导致的n2 log(n)性能。
合并排序可能比你可以做的大多数搜索算法更好。
我是通过以下方式做到的。 号码和名称是两个arraylist。我必须对名称进行排序。如果任何更改都发生在名称为arralist order的情况下,则数字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);
}
}
}
}
}
使用此方法:
private ArrayList<myClass> sortList(ArrayList<myClass> list) {
if (list != null && list.size() > 1) {
Collections.sort(list, new Comparator<myClass>() {
public int compare(myClass o1, myClass o2) {
if (o1.getsortnumber() == o2.getsortnumber()) return 0;
return o1.getsortnumber() < o2.getsortnumber() ? 1 : -1;
}
});
}
return list;
}
`
并使用:mySortedlist = sortList(myList);
无需在您的班级中实施比较器。
如果您想要逆序交换1
和-1
您应该使用Arrays.sort函数。包含的类应该实现Comparable。