• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Java | TreeSet
  1. Notes
  2. Example
  3. Example: Comparator

  1. Notes
    Objects must implement java.lang.Comparable<T> (Exception: cannot be cast to java.lang.Comparable)
    Sorted collection
    null elements not allowed
    Duplicates elements not allowed (hash code)
  2. Example
    TreeSet<String> ts = new TreeSet<>();
    
    // ts.add(null); // java.lang.NullPointerException
    ts.add("c");
    ts.add("bb");
    ts.add("bb");
    ts.add("aaa");
    ts.add("aaa");
    ts.add("aaa");
    
    ts.forEach(System.out::println);
    Output:
    aaa
    bb
    c
  3. Example: Comparator
    TreeSet<String> ts = new TreeSet<>(Comparator.comparing(String::length));
    
    // ts.add(null); // java.lang.NullPointerException
    ts.add("c");
    ts.add("bb");
    ts.add("bb");
    ts.add("aaa");
    ts.add("aaa");
    ts.add("aaa");
    
    ts.forEach(System.out::println);
    Output:
    c
    bb
    aaa
© 2025  mtitek