Syntax error Retrieve the first entry in the TreeMap in Java

Retrieve the first entry in the TreeMap in Java



Use the firstEntry() method in TreeMap to retrieve the first entry.

Create a TreeMap and add some 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");

Now, retrieve the first entry

m.firstEntry()

The following is an example to retrieve first entry in 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");
      for(Map.Entry e:m.entrySet()){
         System.out.println(e.getKey()+" "+e.getValue());
      }
      System.out.println("First Entry in Map is "+m.firstEntry());
   }
}

Output

1 India
2 US
3 Australia
4 Netherlands
5 Canada
First Entry in Map is 1=India
Updated on: 2019-07-30T22:30:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements