Collection.unmodifiableMap iteration

Does Colelction.unmodifiableMap support iteration order?

I tried newMap.put (key, Collections.ModifiableMap (oldMap)) Then, when I do newMap.get (key) and iterate, the iteration order seems to change.

How can we protect the iterative order?

+4
source share
3 answers

Check out Collections.unmodifiableSortedMap . This should give you read-only access on your map and maintain a sorted key order.

+4
source

UnmodifiableMap simply delegates all methods except writing. It is ordered exactly the same as the delegate.

If you need to have the same order as the first set, use LinkedHashMap.

+4
source

If we look at the source of Collections.unmodifiableMap , we see that it simply passes it to the UnmodifiableMap class, which simply wraps it. Therefore, it does not change the basic order of cards.

And according to the documentation for unmodifiableMap it says the following:

Returns the unchanged view of the specified map.

Since he says he is returning the view, this implies that we are not getting another map, just a different way of accessing the old map.

+1
source

Source: https://habr.com/ru/post/1342215/


All Articles