Skip to content
Related Articles

Related Articles

Getting Set View of Keys from HashMap in Java

Improve Article
Save Article
  • Last Updated : 19 Feb, 2021
Improve Article
Save Article

The HashMap class of Java provides the functionality of the hash table data structure. This class is found in the java.util package. It implements the Map interface. It stores elements in (Key, Value) pairs and you can access them by an index of another type (e.g. Integer/String). Here, keys are used as identifiers which are used to associate each value on a map. It can store different types: Integer keys and String values or same types: Integer keys and Integer values.


Given : HashMap = {[a, 1], [b, 3], [C, 1]} 
Output: Keys = [a, b, c]

Given : HashMap<Key, Value> = {[2, "hello"], [1, "world"]} 
Output: Keys = [2, 1]

HashMap is similar to HashTable, but it is unsynchronized. It is allowed to store null keys as well, but there can only be one null key and there can be any number of null values.

HashMap <Integer,String> GFG = new HashMap <Integer,String>();   

// Above is the declaration of HashMap object with Integer keys and String values

The Set interface present in java.util package is an unordered collection of objects in which duplicate values cannot be stored

Set <Obj> set = new HashSet<Obj>( );
// Obj is the type of object to be stored in the Set

The Set view of the keys from HashMap returns the set of all keys in the HashMap in the form of a Set.

Print Keys:

  • Using Iterator object print all keys from while loop
  • Print set object directly passing in System.out.println().



// Getting Set view of keys from HashMap in Java
import java.util.*;
class GFG {
    public static void main(String[] args)
        HashMap<Integer, String> GFG
            = new HashMap<Integer, String>();
        // Inserting 1 as key and Geeks as the value
        GFG.put(1, "Geeks");
        // Inserting 2 as key and For as the value
        GFG.put(2, "For");
        // Inserting 3 as key and Geeks as the value
        GFG.put(3, "Geeks");
        Set<Integer> Geeks = GFG.keySet();
        System.out.println("Set View of Keys in HashMap : "
                           + Geeks);


Set View of Keys in HashMap : [1, 2, 3]
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!