我读过关于使用比较器排序数组列表的内容,但在所有的例子中,人们都使用了compareTo,根据一些研究,它是字符串的一种方法。
我想根据自定义对象的一个属性(Date对象)对其数组列表进行排序
(getStartDay())。通常我通过item1.getStartDate().before(item2.getStartDate())比较它们,所以我想知道我是否可以写一些像这样的东西:
public class CustomComparator {
public boolean compare(Object object1, Object object2) {
return object1.getStartDate().before(object2.getStartDate());
}
}
public class RandomName {
...
Collections.sort(Database.arrayList, new CustomComparator);
...
}
因为技术每天都在出现,所以答案会随着时间的推移而改变。我看了一下LambdaJ,看起来很有趣。
您可以尝试使用LambdaJ解决这些任务。你可以在这里找到它:http://code.google.com/p/lambdaj/
这里有一个例子:
这种迭代
List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
}
});
用排序
List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge());
当然,拥有这种美感会影响性能(平均2次),但你能找到更可读的代码吗?
是的,这是可能的,例如在这个答案中,我根据类IndexValue的属性v进行排序
// Sorting by property v using a custom comparator.
Arrays.sort( array, new Comparator<IndexValue>(){
public int compare( IndexValue a, IndexValue b ){
return a.v - b.v;
}
});
如果您注意到这里,我正在创建一个匿名的内部类(这是用于闭包的Java),并将其直接传递给类Arrays的排序方法
您的对象也可以实现Comparable(这是String和Java中的大多数核心库所做的),但这将定义类本身的“自然排序顺序”,并且不允许您插入新的类。
是的,你可以。比较项有两个选项,Comparable接口和Comparator接口。
这两个接口都允许不同的行为。Comparable允许您使对象的行为与您刚刚描述的String类似(实际上,String实现了Comparable)。第二个,Comparator,允许你做你要求做的事情。你会这样做:
Collections.sort(myArrayList, new MyComparator());
这将导致收集。方法来使用比较器的排序机制。如果数组列表中的对象实现了可比性,你可以这样做:
Collections.sort(myArrayList);
Collections类包含许多这些有用的常用工具。