xpages-noob
xpages-noob

Reputation: 1579

Is there a LinkedHashMap-like class where the entry that is PUT last is also the last in order?

In a LinkedHashMap the entries are by default sorted by insertion order. The construction parameter "accessOrder" allows to change the sorting such that the last entry is the one that was ACCESSED last.

However, I do need a map where the sorting only changes when entries are added or overwritten via PUT (put, putAll, ...). Furthermore, the given map should directly provide a reverse iterator, i.e. without having to create a reversed array of the map's keySet to iterate over.

Does anyone know an existing Java class that provides what I'm searching for?


PS: It would be great if the map would allow concurrent modifications, but that is not essential as I can also synchronize the access manually.

Upvotes: 2

Views: 102

Answers (1)

M. Justin
M. Justin

Reputation: 21132

Java 21 added functionality to LinkedHashMap that allows the addition of elements to the end of the map, as well as return a reversed view of the map. Both of these methods are defined by the new SequencedMap interface that LinkedHashMap now implements.

SequencedMap<String, Integer> map = new LinkedHashMap<>();
map.putLast("A", 1);
map.putLast("B", 2);
map.putLast("A", 3);
map.putLast("C", 4);

System.out.println(map); // {B=2, A=3, C=4}
System.out.println(map.reversed()); // {C=4, A=3, B=2}

The putLast method adds the element to the end of the map, moving it to the end if it's already present:

Inserts the given mapping into the map if it is not already present, or replaces the value of a mapping if it is already present (optional operation). After this operation completes normally, the given mapping will be present in this map, and it will be the last mapping in this map's encounter order.

If this map already contains a mapping for this key, the mapping is relocated if necessary so that it is last in encounter order.

Note that this does require using the putLast method, and not the put or putAll methods, so it doesn't quite meet your stated requirements. But depending on how you're using the map, this might be sufficient.

The reversed method returns a reversed view of the LinkedHashMap:

Returns a reverse-ordered view of this map. The encounter order of mappings in the returned view is the inverse of the encounter order of mappings in this map. The reverse ordering affects all order-sensitive operations, including those on the view collections of the returned view. If the implementation permits modifications to this view, the modifications "write through" to the underlying map. Changes to the underlying map might or might not be visible in this reversed view, depending upon the implementation.

Modifications to the reversed view and its map views are permitted and will be propagated to this map. In addition, modifications to this map will be visible in the reversed view and its map views.

Upvotes: 0

Related Questions