Вопрос

According to Set documentation:

LinkedHashSet iterates in the insertion order of its elements, and a sorted set like SplayTreeSet iterates the elements in sorted order.

So, if you want set functionality and you control the order of iteration, SplayTreeSet is the correct choice.

But how would you efficiently iterate over the set in reverse order (like STL reverse_iterator)? In certain scenarios I want to go forward and in others I want the reverse.

Это было полезно?

Решение

For now splay.toList().reversed seems the way to do that. You can perhaps file an issue to add a reversed property on SplayTreeSet.

Другие советы

There is no way to go backwards.

Having reversed on SplayTreeSet would make a kind of sense. It would be based on the same tree, but just swap the meaning of first/last and the iteration order.

Often creating the set with the reversed Comparator would be enough, but if you want to go both ways on the same map, or don't know the direction before creating the set, there is no simple solution.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top