Java TreeMap firstEntry() Method Example

The entrySet() method of java.util.TreeMap class returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. whereas firstEntry() method returns a key-value mapping associated with the least key in this map, or null if the map is empty.

Signature

public Map.Entry<K,V> firstEntry()

This method returns a key-value mapping associated with the least key in this map, or null if the map is empty.

Example

The following example shows the usage of java.util.TreeMap.firstEntry() method.

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class FirstEntryMethodTreeMapExample
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to populate elements to the TreeMap
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(1,"Element1");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //get the entrySet of treeMap1
        Set<Map.Entry<Integer,String>> set1 = treeMap1.entrySet();.
        //Print the elements of treeMap1
        System.out.println("**Elements of treeMap1**");
        for (Map.Entry<Integer,String> me : set1) 
        {
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        
        //Get the least key of the Map
        System.out.println("**First entry of the TreeMap**");
        System.out.println(treeMap1.firstEntry());
    }
}

Output

**Elements of treeMap1**
1: Element1
2: Element2
3: Element3
4: Element4
5: Element5
**First entry of the TreeMap
1=Element1

Leave a Reply

Your email address will not be published. Required fields are marked *