我有一个名为Person
的类,它有多个属性,例如:
public class Person {
private int id;
private String name, address;
// Many more properties.
}
许多Person
- 对象存储在ArrayList<Person>
中。我想通过多个排序参数对此列表进行排序,并且不时会有所不同。例如,我可能有一次希望按name
升序然后address
降序排序,而另一次按id
降序排序。
而且我不想创建自己的排序方法(即,我想使用Collections.sort(personList, someComparator)
。实现此目的的最优雅解决方案是什么?
答案 0 :(得分:193)
我认为你的枚举方法基本上是合理的,但是switch语句确实需要更加面向对象的方法。考虑:
enum PersonComparator implements Comparator<Person> {
ID_SORT {
public int compare(Person o1, Person o2) {
return Integer.valueOf(o1.getId()).compareTo(o2.getId());
}},
NAME_SORT {
public int compare(Person o1, Person o2) {
return o1.getFullName().compareTo(o2.getFullName());
}};
public static Comparator<Person> decending(final Comparator<Person> other) {
return new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return -1 * other.compare(o1, o2);
}
};
}
public static Comparator<Person> getComparator(final PersonComparator... multipleOptions) {
return new Comparator<Person>() {
public int compare(Person o1, Person o2) {
for (PersonComparator option : multipleOptions) {
int result = option.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
};
}
}
使用示例(使用静态导入)。
public static void main(String[] args) {
List<Person> list = null;
Collections.sort(list, decending(getComparator(NAME_SORT, ID_SORT)));
}
答案 1 :(得分:26)
你可以为你想要排序的每个属性创建比较器,然后尝试“比较器链接”:-)像这样:
public class ChainedComparator<T> implements Comparator<T> {
private List<Comparator<T>> simpleComparators;
public ChainedComparator(Comparator<T>... simpleComparators) {
this.simpleComparators = Arrays.asList(simpleComparators);
}
public int compare(T o1, T o2) {
for (Comparator<T> comparator : simpleComparators) {
int result = comparator.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
}
答案 2 :(得分:16)
一种方法是创建一个Comparator
,它将要排序的属性列表作为参数,如本例所示。
public class Person {
private int id;
private String name, address;
public static Comparator<Person> getComparator(SortParameter... sortParameters) {
return new PersonComparator(sortParameters);
}
public enum SortParameter {
ID_ASCENDING, ID_DESCENDING, NAME_ASCENDING,
NAME_DESCENDING, ADDRESS_ASCENDING, ADDRESS_DESCENDING
}
private static class PersonComparator implements Comparator<Person> {
private SortParameter[] parameters;
private PersonComparator(SortParameter[] parameters) {
this.parameters = parameters;
}
public int compare(Person o1, Person o2) {
int comparison;
for (SortParameter parameter : parameters) {
switch (parameter) {
case ID_ASCENDING:
comparison = o1.id - o2.id;
if (comparison != 0) return comparison;
break;
case ID_DESCENDING:
comparison = o2.id - o1.id;
if (comparison != 0) return comparison;
break;
case NAME_ASCENDING:
comparison = o1.name.compareTo(o2.name);
if (comparison != 0) return comparison;
break;
case NAME_DESCENDING:
comparison = o2.name.compareTo(o1.name);
if (comparison != 0) return comparison;
break;
case ADDRESS_ASCENDING:
comparison = o1.address.compareTo(o2.address);
if (comparison != 0) return comparison;
break;
case ADDRESS_DESCENDING:
comparison = o2.address.compareTo(o1.address);
if (comparison != 0) return comparison;
break;
}
}
return 0;
}
}
}
然后可以在代码中使用它,例如:
cp = Person.getComparator(Person.SortParameter.ADDRESS_ASCENDING,
Person.SortParameter.NAME_DESCENDING);
Collections.sort(personList, cp);
答案 3 :(得分:8)
一种方法是撰写Comparator
。这可能是一个库方法(我确定它存在于某处)。
public static <T> Comparator<T> compose(
final Comparator<? super T> primary,
final Comparator<? super T> secondary
) {
return new Comparator<T>() {
public int compare(T a, T b) {
int result = primary.compare(a, b);
return result==0 ? secondary.compare(a, b) : result;
}
[...]
};
}
使用:
Collections.sort(people, compose(nameComparator, addressComparator));
或者,请注意Collections.sort
是一种稳定的排序。如果性能不是绝对至关重要,则排序为主要之前的次要订单。
Collections.sort(people, addressComparator);
Collections.sort(people, nameComparator);
答案 4 :(得分:4)
比较器可让您轻松自然地完成此操作。您可以在Person类本身或与您需要相关的Service类中创建单个比较器实例 示例,使用匿名内部类:
public static final Comparator<Person> NAME_ASC_ADRESS_DESC
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
int nameOrder = p1.getName().compareTo(p2.getName);
if(nameOrder != 0) {
return nameOrder;
}
return -1 * p1.getAdress().comparedTo(p2.getAdress());
// I use explicit -1 to be clear that the order is reversed
}
};
public static final Comparator<Person> ID_DESC
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return -1 * p1.getId().comparedTo(p2.getId());
// I use explicit -1 to be clear that the order is reversed
}
};
// and other comparator instances as needed...
如果您有很多,您也可以以您喜欢的方式构建比较器代码。例如,您可以:
答案 5 :(得分:2)
我认为将分拣机耦合到Person类,就像你的答案一样,不是一个好主意,因为它将比较(通常是业务驱动的)和模型对象相互接近。 每次你想要改变/添加分拣机的东西时,你需要触摸人类,这通常是你不想做的事情。
使用服务或类似的东西,它提供了像KLE提出的Comparator实例,听起来更灵活,更具扩展性。
答案 6 :(得分:2)
我的方法是建立在Yishai的基础之上。主要差距是没有办法对属性进行首先升序排序,然后对另一个属性进行降序排序。使用枚举无法做到这一点。为此,我使用了课程。因为SortOrder强烈依赖于我更喜欢将其实现为人的内部类的类型。
班级&#39;人员&#39;内部班级&#39; SortOrder&#39;:
import java.util.Comparator;
public class Person {
private int id;
private String firstName;
private String secondName;
public Person(int id, String firstName, String secondName) {
this.id = id;
this.firstName = firstName;
this.secondName = secondName;
}
public abstract static class SortOrder implements Comparator<Person> {
public static SortOrder PERSON_ID = new SortOrder() {
public int compare(Person p1, Person p2) {
return Integer.valueOf(p1.getId()).compareTo(p2.getId());
}
};
public static SortOrder PERSON_FIRST_NAME = new SortOrder() {
public int compare(Person p1, Person p2) {
return p1.getFirstName().compareTo(p2.getFirstName());
}
};
public static SortOrder PERSON_SECOND_NAME = new SortOrder() {
public int compare(Person p1, Person p2) {
return p1.getSecondName().compareTo(p2.getSecondName());
}
};
public static SortOrder invertOrder(final SortOrder toInvert) {
return new SortOrder() {
public int compare(Person p1, Person p2) {
return -1 * toInvert.compare(p1, p2);
}
};
}
public static Comparator<Person> combineSortOrders(final SortOrder... multipleSortOrders) {
return new Comparator<Person>() {
public int compare(Person p1, Person p2) {
for (SortOrder personComparator: multipleSortOrders) {
int result = personComparator.compare(p1, p2);
if (result != 0) {
return result;
}
}
return 0;
}
};
}
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getSecondName() {
return secondName;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("Person with id: ");
result.append(id);
result.append(" and firstName: ");
result.append(firstName);
result.append(" and secondName: ");
result.append(secondName);
result.append(".");
return result.toString();
}
}
使用Person类及其SortOrder的示例:
import static multiplesortorder.Person.SortOrder.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import multiplesortorder.Person;
public class Application {
public static void main(String[] args) {
List<Person> listPersons = new ArrayList<Person>(Arrays.asList(
new Person(0, "...", "..."),
new Person(1, "...", "...")
));
Collections.sort(listPersons, combineSortOrders(PERSON_FIRST_NAME, invertOrder(PERSON_ID)));
for (Person p: listPersons) {
System.out.println(p.toString());
}
}
}
oRUMOo
答案 7 :(得分:0)
我最近编写了一个Comparator来对分隔的String记录中的多个字段进行排序。它允许您定义分隔符,记录结构和排序规则(其中一些是特定于类型的)。您可以通过将Person记录转换为分隔的String来使用它。
所需信息以编程方式或通过XML文件播种到Comparator本身。
XML由包嵌入的XSD文件验证。例如,下面是制表符分隔的记录布局,其中包含四个字段(其中两个是可排序的):
<?xml version="1.0" encoding="ISO-8859-1"?>
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<delimiter>	</delimiter>
<column xsi:type="Decimal">
<name>Column One</name>
</column>
<column xsi:type="Integer">
<name>Column Two</name>
</column>
<column xsi:type="String">
<name>Column Three</name>
<sortOrder>2</sortOrder>
<trim>true</trim>
<caseSensitive>false</caseSensitive>
<stripAccents>true</stripAccents>
</column>
<column xsi:type="DateTime">
<name>Column Four</name>
<sortOrder>1</sortOrder>
<ascending>true</ascending>
<nullLowSortOrder>true</nullLowSortOrder>
<trim>true</trim>
<pattern>yyyy-MM-dd</pattern>
</column>
</row>
然后你会在java中使用它:
Comparator<String> comparator = new RowComparator(
new XMLStructureReader(new File("layout.xml")));
图书馆可以在这里找到:
答案 8 :(得分:0)
假设有一个类Coordinate
,并且必须根据X坐标和Y坐标以两种方式对其进行排序。它需要两个不同的比较器。以下是样本
class Coordinate
{
int x,y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
static Comparator<Coordinate> getCoordinateXComparator() {
return new Comparator<Coordinate>() {
@Override
public int compare(Coordinate Coordinate1, Coordinate Coordinate2) {
if(Coordinate1.x < Coordinate2.x)
return 1;
else
return 0;
}
// compare using Coordinate x
};
}
static Comparator<Coordinate> getCoordinateYComparator() {
return new Comparator<Coordinate>() {
@Override
public int compare(Coordinate Coordinate1, Coordinate Coordinate2) {
if(Coordinate1.y < Coordinate2.y)
return 1;
else
return 0;
}
// compare using Coordinate y
};
}
}