javaiteratorreverseconcurrentskiplistmap

Iterate a Java ConcurrentSkipListMap in reverse


I have a map with some values:

public ConcurrentMap<Long, Double> data = new ConcurrentSkipListMap<>();

How do I iterate this in reverse?
Java iterator doesn't seem to have an next() function or a function to reverse the map.


Solution

  • ConcurrentSkipListMap implements ConcurrentNavigableMap, which has a descdendingMap() method returning view of this map ordered in reverse:

    Iterator<Entry<Long, Double>> reversed = data.descendingMap().entrySet().iterator();
    

    However, CSLM reversed iterator is much slower than direct iterator (O(log N) vs O(1) for each next()) and thus should be used only if required rarely. Otherwise consider creating the map using "reversed" custom comparator:

    data = new ConcurrentSkipListMap<>((k1, k2) -> Long.compare(k2, k1));