不使用Map时TreeSet中按id查找Person的高效实现方法
优化方案
你的Person类已经以id为唯一判断标准实现了Comparable接口,而TreeSet本身是基于红黑树实现的有序集合,原生支持O(logn)级别的元素定位,完全不需要将全量元素拷贝到ArrayList中做二分查找。
实现代码
public Person findPersonById(int id) { Person pattern = new Person(id); // 查找TreeSet中大于等于pattern的最小元素 Person matchedCandidate = idTreeSet.ceiling(pattern); // 校验找到的元素是否和目标id完全匹配 return matchedCandidate != null && matchedCandidate.equals(pattern) ? matchedCandidate : null; }
方案说明
- 时间复杂度为O(log n),远优于原实现的O(n):
ceiling方法底层直接基于红黑树结构查找,不需要遍历全量元素,也没有集合拷贝的开销。 - 逻辑完全可靠:你的Person类的
compareTo、equals方法逻辑完全对齐,均以id作为唯一判断依据,符合TreeSet的使用约定。如果集合中不存在对应id的元素,ceiling会返回null或者id更大的元素,通过equals判断即可过滤不匹配的情况。
内容的提问来源于stack exchange,提问作者Alexander Tukanov
相关产品推荐
相关产品推荐

