keySet( ) method of Map Interface in Java.

keySet( ) method of Map Interface in Java.


Posted in : Core Java Posted on : February 18, 2011 at 8:20 PM Comments : [ 0 ]

In this section we will discuss how can keySet( ) method be implemented in Map interface in java. Set keySet() This method returns a set of keys that are contained into the underlying map.

keySet( ) method of Map Interface in Java.

In this section we will discuss how can keySet( ) method be implemented in Map interface in java.

Syntax

Set<K> keySet()

This method returns a set of keys that are contained into the underlying map.

In this method the resultant Set object is returned by the Map therefore any modifications to the Map are shown into the set, and vice-versa. If any key that is removed from Set will also be removed from original Map object but, the same does not occur with addition, as it does not support the add or addAll operations. If any modification occurs during the process of iteration over the set during processing, the effects of the iteration are undefined.

Parameter description

This method has no parameter but, it returns a set of keys contained in the underlying map.

Example of keySet() method

In this example we will show how does keySet() method work in Map interface. This example will help you to understand how you can find a set of keys that contained into the underlying map. Further we will show you what happens when we modified into the set of keys.

Example :

package devmanuals.com;
import java.util.Map;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Set;
public class MapKeySet {
  public static void main(String[] args) {
    Map<String,Integer> mp= new HashMap<String,Integer>();
    mp.put("A"1);
    mp.put("B"2);
    mp.put("C", 3);
    System.out.println("Mappings are ="+mp);
    Set st = mp.keySet();
    System.out.println("Set of keyes are : "+st);
    Iterator itr = st.iterator();
    while (itr.hasNext())
    System.out.println(itr.next());
     //remove B from Set
    st.remove("B");
    // check that original Map still contains B
    boolean bol = mp.containsKey("B");
    System.out.println("Does Map contain 2 ? " + bol);
    System.out.println("After modification mappings are = "+mp);
  }
}

Output :

Mappings are ={A=1, B=2, C=3}

Set of keyes are : [A, B, C]

A

B

C

Does Map contain 2 ? false

After modification mappings are = {A=1, C=3}

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics