TreeSet如何实现自定义排序

avatar
作者
猴君
阅读量:0

要实现自定义排序,需要在创建TreeSet对象时传入一个Comparator对象,该对象定义了元素的比较规则。

例如,假设有一个类Person,需要按照年龄从小到大排序:

import java.util.Comparator; import java.util.TreeSet;  class Person {     String name;     int age;      public Person(String name, int age) {         this.name = name;         this.age = age;     }      public String getName() {         return name;     }      public int getAge() {         return age;     } }  public class Main {     public static void main(String[] args) {         TreeSet<Person> treeSet = new TreeSet<>(new Comparator<Person>() {             @Override             public int compare(Person p1, Person p2) {                 return Integer.compare(p1.getAge(), p2.getAge());             }         });          treeSet.add(new Person("Alice", 25));         treeSet.add(new Person("Bob", 30));         treeSet.add(new Person("Charlie", 20));          for (Person person : treeSet) {             System.out.println(person.getName() + " " + person.getAge());         }     } } 

在上面的代码中,创建了一个TreeSet对象treeSet并传入了一个Comparator对象,定义了按照Person对象的age属性进行排序的规则。最后输出结果为:

Charlie 20 Alice 25 Bob 30 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!