使用比较器降序排序(用户定义的类)

我想使用比较器按降序对对象进行排序。


class Person {

 private int age;

}

在这里,我想对一个Person对象数组进行排序。


我怎样才能做到这一点?


RISEBY
浏览 514回答 3
3回答

慕勒3428872

您可以用这种方法来覆盖用户定义的类的降序方法,从而覆盖compare()方法,Collections.sort(unsortedList,new Comparator<Person>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public int compare(Person a, Person b) {&nbsp; &nbsp; &nbsp; &nbsp; return b.getName().compareTo(a.getName());&nbsp; &nbsp; }});或通过使用Collection.reverse()用户Prince在其评论中提到的降序进行排序。您可以像这样进行升序排序,Collections.sort(unsortedList,new Comparator<Person>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public int compare(Person a, Person b) {&nbsp; &nbsp; &nbsp; &nbsp; return a.getName().compareTo(b.getName());&nbsp; &nbsp; }});我们用简洁的Lambda表达式(从Java 8开始)替换上面的代码:Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));从Java 8开始,List具有sort()方法,该方法将Comparator作为参数(更简洁):personList.sort((a,b)->b.getName().compareTo(a.getName()));在这里a,b由lambda表达式推断为Person类型。

慕婉清6462132

我将为人员类创建一个比较器,该比较器可以通过某种排序行为进行参数化。在这里,我可以设置排序顺序,但是可以对其进行修改以允许对其他人员属性进行排序。public class PersonComparator implements Comparator<Person> {&nbsp; public enum SortOrder {ASCENDING, DESCENDING}&nbsp; private SortOrder sortOrder;&nbsp; public PersonComparator(SortOrder sortOrder) {&nbsp; &nbsp; this.sortOrder = sortOrder;&nbsp; }&nbsp; @Override&nbsp; public int compare(Person person1, Person person2) {&nbsp; &nbsp; Integer age1 = person1.getAge();&nbsp; &nbsp; Integer age2 = person2.getAge();&nbsp; &nbsp; int compare = Math.signum(age1.compareTo(age2));&nbsp; &nbsp; if (sortOrder == ASCENDING) {&nbsp; &nbsp; &nbsp; return compare;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; return compare * (-1);&nbsp; &nbsp; }&nbsp; }}(希望它现在可以编译,我手边没有IDE或JDK,编码为“ blind”)编辑感谢Thomas,编辑了代码。我不会说Math.signum的用法很好,高效,有效,但是我想提醒一下,compareTo方法可以返回任何整数,并且如果()乘以(-1)将失败。实现返回Integer.MIN_INTEGER ...并且我删除了setter,因为它便宜得足以在需要时构造一个新的PersonComparator。但是我保留拳击内容,因为它表明我依赖现有的Comparable实现。可以做类似的事情,Comparable<Integer> age1 = new Integer(person1.getAge());但是看起来太难看了。这个想法是要显示一种模式,该模式可以轻松地适应其他“人”属性,例如姓名,生日作为“日期”等等。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java