Skip to content

Remove First or Last Entry (mapping) from Java TreeMap Example

This example shows how to remove the first or last entry from the TreeMap in Java. The example also shows how to remove the first or last key value from the TreeMap.

How to remove first or last entry from the TreeMap in Java?

1. How to remove first entry from the TreeMap?

There are a couple of ways using which you can remove the first key-value mapping from the TreeMap as given below.

Using the pollFirstEntry method

The pollFirstEntry method returns and removes the first entry from the map object.

It removes and returns the first key-value mapping from the map or null if the TreeMap is empty.

Output

Using the firstKey method

We can also get the first key from the TreeMap using the firstKey method and then remove the mapping from the TreeMap using the remove method as given below.

Output

2. How to remove last entry from the TreeMap?

There are a couple of ways using which you can remove the last key-value mapping from the TreeMap as given below.

Using the pollLastEntry method

The pollLastEntry method removes and returns the last entry from the TreeMap object.

The pollLastEntry method returns null if the TreeMap is empty.

Output

Using the lastKey method

We can also get the last key from the TreeMap using the lastKey method and then remove the mapping from the TreeMap using the remove method as given below.

Output

This example is a part of the TreeMap in Java Tutorial.

Please let me know your views in the comments section below.

References:
Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.