user3675773
user3675773

Reputation:

How to remove first element from a TreeMap?

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

Answers (2)

Mahfuz
Mahfuz

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

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

Use LinkedHashMap, which has method removeEldestEntry.

Upvotes: 0

Related Questions