Switch to full style
Java Collections classes examples .
Post a reply

Print the content of hashMap object

Mon Oct 22, 2012 8:23 pm

Display the content of hashMap, check if contains a key, print its size, remove its content and finally check it if empty
Code:

import java
.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class 
ArraysWork {

    public static 
void main(String[] arr) {

        
/* Create object of HashMap */

        
HashMap<StringStringhashMap = new HashMap<StringString>();

        
/* Add entries to hashMap (Keys,Values) */
        
hashMap.put("A""Apple");
        
hashMap.put("B""Book");
        
hashMap.put("C""Car");
        
hashMap.put("D""Dog");
        
hashMap.put("E""Elephant");
        
hashMap.put("F""Flower");

        
// Print the content of the hashMap
        
Set<Entry<String,String>> hashSet=hashMap.entrySet();
        for(
Entry entry:hashSet ) {

            
System.out.println("Key="+entry.getKey()+", Value="+entry.getValue());
        }
        
System.out.println("-----------------------------");
        
// Print the size of hashMap
         
System.out.println("HashMap size="+hashMap.size());

        
// Checking and searching
        
if(hashMap.containsKey("X")) {
             
System.out.println("HashMap has a key X");
        }else{
             
System.out.println("HashMap hasn't a key X");
        }

         
// Remove the content of the hashMap
         
hashMap.clear();

         
// Check if the hashMap empty
         
if(hashMap.isEmpty())
         {
             
System.out.println("The hashMap is empty");
         }


    }
}
 


The output is :
Code:
Key=D, Value=Dog
Key=E, Value=Elephant
Key=F, Value=Flower
Key=A, Value=Apple
Key=B, Value=Book
Key=C, Value=Car
-----------------------------
HashMap size=6
HashMap hasn't a key X
The hashMap is empty




Post a reply
  Related Posts  to : Print the content of hashMap object
 print to console using the cout object with different Color     -  
 Read file content to StringBuffer String object     -  
 how to show hashmap value in a textbox     -  
 HashMap class with generics     -  
 Help for Print using php     -  
 Print the ASCII Set     -  
 Print all files in a directory     -  
 print element in 2d matrix     -  
 Difference between PHP echo() and PHP print()?     -  
 Print all server variables     -  

Topic Tags

Java Collections