Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 207
Waltari Avatar asked Nov 02 '25 11:11

Waltari


1 Answers

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));
like image 138
Alex Salauyou Avatar answered Nov 05 '25 03:11

Alex Salauyou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!