The iterator returned by the TreeSet does not support moving forward and backward. Therefore, if going back and forth is a difficult requirement, you need to first create a list and get a list iterator from it:
List<T> list = new ArrayList<>(treeSet); int index = list.indexOf(object); ListIterator<T> iterator = list.listIterator(index);
If you want to use an iterator to change the set, this is not an option, because obviously you have to change the list, not the set.
If TreeSet is not a strict requirement, you can create a subset of your TreeSet and get an iterator from it:
Navigable<T> subset = treeSet.tailSet(object); Iterator<T> iterator = subset.iterator();
This is pretty fast because tailSet returns a representation of this subset, so it does not require a copy of part of the set.
source share