Remove the first entry of the TreeMap in Java


To remove the first entry of the TreeMap, use the pollFirstEntry() method.

Let us first create a TreeMap and add elements −

TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"India");
m.put(2,"US");
m.put(3,"Australia");
m.put(4,"Netherlands");
m.put(5,"Canada");

Remove the first entry now −

m.pollFirstEntry()

The following is an example to remove the first entry of the TreeMap.

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"India");
      m.put(2,"US");
      m.put(3,"Australia");
      m.put(4,"Netherlands");
      m.put(5,"Canada");
      System.out.println("TreeMap Elements = "+m);
      System.out.println("Removing First Entry : "+m.pollFirstEntry());
      System.out.println("Updated TreeMap Elements = "+m);
   }
}

Output

TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands, 5=Canada}
Removing First Entry = 1=India
Updated TreeMap Elements = {2=US, 3=Australia, 4=Netherlands, 5=Canada}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements