温馨提示×

TreeSet如何实现自定义排序

小樊
83
2024-06-26 22:03:01
栏目: 编程语言

要实现自定义排序,需要在创建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

0