简体   繁体   English

Java,TreeSet。 我们可以从第一个元素开始迭代元素吗?

[英]Java, TreeSet. Can we iterate elements from not first element?

Good day. 美好的一天。

I use TreeSet , for example TreeSet<Integer> t . 我使用TreeSet ,例如TreeSet<Integer> t And I want to print all numbers from set t between x and y. 而且我想从x和y之间的set t打印所有数字。

void print(Integer x,Integer y, TreeSet<Integer> t){
...
}

How to do it? 怎么做? Of Course I can get t.iterator() , and iterator all numbers from set and check is it greats x and less y. 当然,我可以得到t.iterator() ,并迭代set中的所有数字并检查x是否t.iterator() y。 Time complexity is y steps. 时间复杂度是y步。 but if yx is small. 但是如果yx小。 It will be better to get t.higher() and after that iterate the elements in set until it less than y. 最好获得t.higher(),然后迭代set中的元素,直到小于y。 This solution can be implemented in C++. 该解决方案可以用C ++实现。 And it's time complexity is log (t.size())+(yx) . 它的时间复杂度是log (t.size())+(yx)

How to do in in Java? 用Java怎么做?

You can use the SortedSet interface (which TreeSet implements). 您可以使用SortedSet接口( TreeSet实现)。 For example: 例如:

SortedSet<Integer> set = new TreeSet<Integer>();

for (int i = 1; i <= 5; ++i) {
    set.add(i);
}

int from = 2;
int to = 4;
for (int x : set.subSet(from, to+1)) { // Note that the higher bound is exclusive.
    System.out.println(x);
}

Output: 输出:

2
3
4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM