Java提供内置实用程序方法*sort()和Comparator集合。reverseOrder()*按降序对对象排序。
Collections.sort(persons, Collections.reverseOrder());
这个示例演示了我们创建一个person对象列表,并使用Comparable接口的*compateTo()*方法比较每个人的年龄。简而言之,我们正在按年龄降序对人进行分类。
ij1k1l
public class Person implements Comparable < Person > {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
@Override
public int compareTo(Person otherPerson) {
return (this.getAge() - otherPerson.getAge());
}
}
注意,Person类实现Comparable接口并提供compareTo()
方法实现。
下面是测试和排序person对象的代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PersonSorterInASC {
public static void main(String[] args) {
sortUserDefinedObjectsInAsc();
}
private static void sortUserDefinedObjectsInAsc() {
List < Person > persons = new ArrayList < Person > ();
Person person1 = new Person(59, "John", 40);
Person person12 = new Person(67, "Roger", 25);
Person person13 = new Person(45, "Steven", 30);
persons.add(person1);
persons.add(person12);
persons.add(person13);
System.out.println("Before Sorting : " + persons);
Collections.sort(persons, Collections.reverseOrder());
System.out.println("After Sorting : " + persons);
}
}
输出:
Before Sorting : [John, Roger, Steven]
Sort in decending order : [John, Steven, Roger]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2019/06/sort-user-defined-objects-in-descending-order-in-java.html
内容来源于网络,如有侵权,请联系作者删除!