Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Iterator start from specific element of sorted set

I have a sorted set in Java (eg a TreeSet). I want to have an iterator starting from a specific element of the tree and be able to go to the next or previous element (in the order of sorting).

Is there any idea of how to do this without implementing my own data structure??

Thanks


EDIT:

I forgot to mention that I want to do it with a naive way (if there is any) since I care about perfomance. If I had access to the implementation of the tree it would take O(1) time to do that. I want something similar.

Also feel free to suggest other (3rd party) implementations of Sorted Trees in java that supports this.

like image 536
ApollonDigital Avatar asked Oct 20 '22 05:10

ApollonDigital


2 Answers

To go forward from element x of SortedSet s, use s.tailSet(x).iterator().

To go backwards from element x of NavigableSet s use s.descendingSet().tailSet(x).iterator().

tailSet() and descendingSet() create views of the original set, s. Their implementation therefore can not create copies of the original set (otherwise the copy would become out of date if the viewed set were changed), and so will have O(1) performance.

A TreeSet is a NavigableSet and thus a SortedSet.

like image 196
Raedwald Avatar answered Nov 15 '22 04:11

Raedwald


You can keep calling continue to skip that iteration until you reach the Object you are looking for. Hard to give much more information without more context

ArrayList list = new ArrayList();
Iterator itr = list.iterator();
boolean skipElement = true;
while(itr.hasNext()) {
    Object element = itr.next();
    if(element.equals(myTargetElement)){ //target element is what you're comparing against to see where you want to start iterating (you didn't supply that info so not sure how you want to handle this)
        skipElement=false;
    }
    if(skipElement){
        continue;
    }
     System.out.print(element);
  }

this will print out the element that you want to start iterating at first.

like image 23
GregH Avatar answered Nov 15 '22 05:11

GregH