2
我有一個包含一些值的映射。在反向中迭代ConcurrentSkipListMap
public ConcurrentMap<Long, Double> data = new ConcurrentSkipListMap<>();
我該如何反向迭代? Java迭代器似乎沒有next()函數或函數來反轉地圖。
我有一個包含一些值的映射。在反向中迭代ConcurrentSkipListMap
public ConcurrentMap<Long, Double> data = new ConcurrentSkipListMap<>();
我該如何反向迭代? Java迭代器似乎沒有next()函數或函數來反轉地圖。
ConcurrentSkipListMap
實現ConcurrentNavigableMap
,其具有此地圖反向有序的descdendingMap()
方法返回視圖:
Iterator<Entry<Long, Double>> reversed = data.descendingMap().entrySet().iterator();
然而,CSLM反向迭代器是比直接迭代器(爲O(log N)VSö較慢多 (1)每個next()
),因此只有在很少需要的情況下才能使用。否則,請考慮使用「反向」自定義比較器創建地圖:
data = new ConcurrentSkipListMap<>((k1, k2) -> Long.compare(k2, k1));
非常聰明的解決方案!它有一個底層比較器來使它具有reverseOrder() – mlewandowski
@mlewandowski它,但是接受入口和索引節點是單鏈接的這一事實,這樣的迭代將會慢得多,因爲索引必須在前進方向上遍歷 –