beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Get Set view of Keys from HashMap

By Chaitanya Singh | Filed Under: Java.util package

Description

Program to get the Set of keys from HashMap.

Example

import java.util.Iterator;
import java.util.HashMap;
import java.util.Set;
class HashMapExample{

  public static void main(String args[]) {
 
    // Create a HashMap
    HashMap<String, String> hmap = new HashMap<String, String>(); 
 
    // Adding few elements
    hmap.put("Key1", "Jack");
    hmap.put("Key2", "Rock");
    hmap.put("Key3", "Rick");
    hmap.put("Key4", "Smith");
    hmap.put("Key5", "Will");
 
    // Getting Set of HashMap keys
    /* public Set<K> keySet(): Returns a Set view of the keys contained
     * in this map. The set is backed by the map, so changes to the map 
     * are reflected in the set, and vice-versa. 
     */
    Set<String> keys = hmap.keySet();

    System.out.println("Set of Keys contains: ");
 
    /* If your HashMap has integer keys then specify the iterator like
     * this: Iterator<Integer> it = keys.iterator();
     */
    Iterator<String> it = keys.iterator();
    // Displaying keys. Output will not be in any particular order
    while(it.hasNext()){
       System.out.println(it.next());
    } 
  }
}

Output:

Set of Keys contains: 
Key2
Key1
Key4
Key3
Key5

Note: The set of keys is backed up by original HashMap so if you remove any key from the Set it would automatically be removed from the HashMap.

Enjoyed this post? Try these related posts

  1. Delete all the elements from HashSet
  2. Difference between HashSet and TreeSet
  3. Iterate a LinkedList in reverse sequential order – java
  4. Adding an element to LinkedList using add(E e) method – Java
  5. Difference between HashSet and HashMap
  6. Converting a HashSet to an Array

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap