Java TreeMap.entrySet() example

In this java tutorial, You will learn how to use entrySet() method of TreeMap class.The entrySet() method is used to return a Set view of the mappings contained in this map. The set's iterator returns the entries in ascending key order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Returns a Set view of the mappings contained in this map.

syntax

public Set<Map.Entry<K,V>> entrySet()

Returns

a set view of the mappings contained in this map.

Java TreeMap entrySet() example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • students.entrySet(); Returns a Set view of the mappings contained in this map.
  • Print Set values.
package com.technicalkeeda;

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

public class App {
    public static void main(String args[]) {

        TreeMap < Integer, String > students = new TreeMap < Integer, String > ();

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");


        Set mapSet = students.entrySet();

        System.out.println("Values:- " + mapSet);

    }
}

output

Values:- [1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi]