Collections(Java)-Map Interface example program
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Hashtable;
public class CollectionsMapDemo {
public static void main(String [] args){
HashMap<Object,Object> map=new HashMap<Object,Object>();
map.put(1, "filter");
map.put("a", "claim");
map.put("3", "smart");
map.put(null,"filter");
map.put(null,"filter");
map.put(4, "sentinal");
map.put(4, "sentinal");
if(!map.isEmpty()){
Iterator<Entry<Object, Object>> it=map.entrySet().iterator();
System.out.println("HashMap can have one null key with multiple values \n");
while(it.hasNext()){
Map.Entry<Object, Object> obj=(Map.Entry<Object, Object>)it.next();
System.out.println(obj.getValue());
}
}
boolean isExist=map.containsKey("3");
boolean valueExist=map.containsValue("sentinal");
if(valueExist==true){
System.out.println("If it is true, then show me the key \n"+map.get(null));
}
System.out.println("Check whether hashMap contains filter as a value? "+valueExist);
System.out.println("Does key 3 exist in HashMap? "+isExist);
if(isExist==true){
System.out.println("If it is true,then show me the value \n"+map.get("3"));
}
System.out.println("\n HashTable can't have any null key or any null values");
Hashtable<Object,Object> table=new Hashtable<Object,Object>();
table.put(1, "filter");
table.put(2, "claim");
table.put("3", "smart");
table.put(4, "sentinal");
table.put(4, "sentinal");
if(!table.isEmpty()){
Iterator<Entry<Object,Object>> its=table.entrySet().iterator();
while(its.hasNext()){
Map.Entry<Object, Object> obj1=(Map.Entry<Object, Object>)its.next();
System.out.println(obj1.getValue());
}
}
boolean findValue=table.containsKey(3);
System.out.println("Does HashTable contains 2 as key? "+findValue);
if(findValue==true){
System.out.println("If it is true,then show me the value \n"+findValue);
}
System.out.println("\n TreeMap");
TreeMap<Object,Object> tree=new TreeMap<Object,Object>();
tree.put(1, "one");
tree.put(2, "two");
tree.put(3, "Three");
tree.put(6, null);
tree.put(4, "four");
tree.put(5, "five");
if(!tree.isEmpty()){
Iterator<Entry<Object,Object>> itrs=tree.entrySet().iterator();
while(itrs.hasNext()){
Map.Entry<Object,Object> obj2=(Map.Entry<Object, Object>)itrs.next();
System.out.println(obj2.getValue());
}
}
}
}
Output:
HashMap can have one null key with multiple values
filter
filter
claim
smart
sentinal
If it is true, then show me the key
filter
Check whether hashMap contains filter as a value? true
Does key 3 exist in HashMap? true
If it is true,then show me the value
smart
HashTable can't have any null key or any null values
smart
sentinal
claim
filter
Does HashTable contains 2 as key? false
TreeMap
one
two
Three
four
five
null
Comments
Post a Comment