Advertisement
Nom1fan

TreeSet example

Aug 1st, 2023
962
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1.     public static void main(String[] args) {
  2.         TreeSet<Person> people = new TreeSet<>();
  3.         people.add(new Person(LocalDateTime.of(1987, 5, 14, 0, 0)));
  4.         people.add(new Person(LocalDateTime.of(2000, 5, 14, 0, 0)));
  5.         people.add(new Person(LocalDateTime.of(2002, 5, 14, 0, 0)));
  6.  
  7.         System.out.println("people: " + people);
  8.         NavigableSet<Person> reversedPeople = people.descendingSet();
  9.         System.out.println("Reversed people: " + reversedPeople);
  10.     }
  11.    
  12.     public static class Person implements Comparable<Person> {
  13.         private final LocalDateTime birthday;
  14.  
  15.         public Person(LocalDateTime birthday) {
  16.             this.birthday = birthday;
  17.         }
  18.  
  19.         @Override
  20.         public int compareTo(Person o) {
  21.             return this.birthday.compareTo(o.birthday);
  22.         }
  23.  
  24.         @Override
  25.         public String toString() {
  26.             return "Person{" +
  27.                     "birthday=" + birthday +
  28.                     '}';
  29.         }
  30.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement