TreeSet Navigable Ranges And Views
Query sorted TreeSet subsets with headSet, tailSet, and subSet, then find floor, ceiling, and polled extremes in log time.
Code
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;
public class TreeSetRanges {
public static void main(String[] args) {
TreeSet<Integer> ports = new TreeSet<>(List.of(22, 80, 443, 3000, 5432, 8080));
System.out.println("sorted: " + ports);
// 视图是区间:subSet 默认左闭右开
System.out.println("subSet 80..3000: " + ports.subSet(80, 3000));
System.out.println("headSet < 443: " + ports.headSet(443));
System.out.println("tailSet >= 3000: " + ports.tailSet(3000));
// floor/ceiling 在值不存在时仍返回最近邻
System.out.println("floor(400): " + ports.floor(400));
System.out.println("ceiling(400): " + ports.ceiling(400));
System.out.println("higher(443): " + ports.higher(443));
System.out.println("lower(80): " + ports.lower(80));
// descendingSet 是同一集合的反向视图
NavigableSet<Integer> descending = ports.descendingSet();
System.out.println("descending: " + descending);
// pollFirst/pollLast 移除并返回极值
System.out.println("pollFirst: " + ports.pollFirst());
System.out.println("pollLast: " + ports.pollLast());
System.out.println("remaining: " + ports);
// 视图受底层集合约束:删除元素会反映到所有视图
NavigableSet<Integer> view = ports.headSet(3000, true);
ports.remove(80);
System.out.println("view after remove: " + view);
}
}How the snippet works
TreeSet Navigable Ranges And Views comes down to the class TreeSetRanges and the function main.
Using it
The run emits 13 labeled sections — sorted:, subSet 80..3000:, headSet < 443:, tailSet >= 3000:, floor(400):, ceiling(400):, higher(443):, lower(80):, descending:, pollFirst:, pollLast:, remaining:, view after remove: — one per step.
Key statements
TreeSet<Integer> ports = new TreeSet<>(List.of(22, 80, 443, 3000, 5432, 8080));
NavigableSet<Integer> descending = ports.descendingSet();
NavigableSet<Integer> view = ports.headSet(3000, true);
Interactive Tools for This Topic
FAQ
- What does TreeSet Navigable Ranges And Views print when run?
- Running the file directly is enough — expect labeled output lines such as `sorted:`, `subSet 80..3000:`, `headSet < 443:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.