← Java from Scratch Lesson 74 of 88 · 10 XP

TreeSet

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

TreeSet keeps its elements sorted (a red-black tree, O(log n) operations) and can find the "nearest" ones:

TreeSet<Integer> t = new TreeSet<>(List.of(10, 3, 7, 25));
t                 // [3, 7, 10, 25]
t.first(), t.last()      // 3, 25
t.floor(9)        // 7  — the largest ≤ 9
t.ceiling(9)      // 10 — the smallest ≥ 9
t.lower(7)        // 3  — strictly less
t.higher(25)      // null — there's no such element
t.headSet(10)     // [3, 7] — less than 10
t.tailSet(10)     // [10, 25]
t.pollFirst()     // take and remove the minimum

The elements must be comparable (Comparable), or you need a Comparator in the constructor.

Task. Bus stops along a highway (in kilometres). Commands: add K — add one, del K — remove one, near K — the stop nearest to K (at an equal distance — the smaller one; if there are no stops — none), list — all of them in order, separated by spaces.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.