Update: My previous answer was wrong. You cannot do it without modifying the default behaviour! See below why.
..how to get the last entry or key entered?
From the API description of LinkedHashMap
you can read:
A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification.
So what does it all mean?
- access-ordered - every time you do a
put
or a get
the order of the elements changes
- insertion-ordered - when inserting elements (for the first time) they are added last
For example:
map.put(1, 1);
map.put(2, 2);
map.put(1, 10);
System.out.println(map);
... will print {1=10, 2=2}
with insertion-ordered and {2=2, 1=10}
with *access-ordered'. The trouble is using access-ordered
if of course if you do a get
operations the order also changes.
How to fix
So... how to fix. Well the LinkedHashMap
cannot be used directly used. So you can wrap it (do not care about the corny name) and override the put
and the putAll
methods so that they remove the key from the map first before putting it back in!
class BestLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
@Override
public V put(K key, V value) {
V last = super.remove(key);
super.put(key, value);
return last;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (K key : m.keySet())
super.remove(key);
super.putAll(m);
}
}
Then to get the last element, either do:
wrap the output from in a LinkedList
implementation:
V v = new LinkedList<V>(map.values()).getLast();
toArray()
way:
Collection<V> values = map.values();
V v = values.toArray(new V[0])[values.size() - 1];
iterate to the last element using the iterator:
Iterator<V> it = values.iterator();
V last = null;
while (it.hasNext())
last = it.next();