Reputation:
I need to implement a container which contains maximum 32 values where elements are sorted by key. In C++ it's kinda easy, cause every map is sorted by it's key, in Java I'm not that sure.
So I read some and came with a TreeMap.
How to efficently remove the oldest element from a TreeMap (the first one)?
Thanks!
Upvotes: 2
Views: 10630
Reputation: 401
You said
The key here is a 'sequenceNumber' which is being incremented in the same loop.
By TreeMap documentation it states
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
So you can easily remove the first element after sorted.
Example:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "ac");
map.put(2, "ef");
map.put(3, "bd");
map.remove(map.firstKey());
Upvotes: 2