Task 3 of 5 · 0 solved · 5 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.3 Ordered collections — TreeSet keeps values sorted

Lesson

То же самое для множества

TreeSet is to HashSet what TreeMap is to HashMap: same behaviour, plus a guaranteed order. Duplicates are still ignored, contains still works, but the values come out sorted.


Worked example

Set<String> s = new TreeSet<String>();
s.add("pear");
s.add("apple");
s.add("fig");
s.add("apple");          // duplicate — ignored, as always
System.out.println(s);   // [apple, fig, pear]
System.out.println(s.size());   // 3

Extras: first() and last() give the smallest and largest values.

So a single line — new TreeSet<>() instead of new HashSet<>() — turns «deduplicate» into «deduplicate and sort».


▶ Try it: run this, then change something and run it again.



A TreeSet stores...


Adding a duplicate to a TreeSet...


Type exactly what this program prints.

import java.util.Set;
import java.util.TreeSet;

public class Main { public static void main(String[] a){
    TreeSet<Integer> t = new TreeSet<Integer>();
    t.add(30);
    t.add(5);
    t.add(17);
    t.add(5);
    System.out.println(t);
    System.out.println(t.size());
}}

To deduplicate a list AND sort it, you use...


True or false?