TreeSet如何實(shí)現(xiàn)自定義排序

小樊
93
2024-06-26 22:03:01

要實(shí)現(xiàn)自定義排序,需要在創(chuàng)建TreeSet對(duì)象時(shí)傳入一個(gè)Comparator對(duì)象,該對(duì)象定義了元素的比較規(guī)則。

例如,假設(shè)有一個(gè)類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());
        }
    }
}

在上面的代碼中,創(chuàng)建了一個(gè)TreeSet對(duì)象treeSet并傳入了一個(gè)Comparator對(duì)象,定義了按照Person對(duì)象的age屬性進(jìn)行排序的規(guī)則。最后輸出結(jié)果為:

Charlie 20
Alice 25
Bob 30

0