How to write a Java method that stores the months of the year and the
number of days of the corresponding month in a collection class, then
goes through the collection and prints the name of the months that only
have 30 days
It contains unique element.
It is an unordered Set.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class CollectionDemo
{
public static void main(String[] args)
{
HashMap<String, Integer> map=new HashMap<String, Integer>();
map.put("jan", 31);
map.put("feb", 28);
map.put("mar", 31);
map.put("apr", 30);
//So on u can add all
//Now iterate through whili loop
Iterator itr=map.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String, Integer> ob=(Map.Entry<String, Integer>)itr.next();
if(ob.getValue()==30)
{
System.out.println("key->"+ob.getKey());
System.out.println("value->"+ob.getValue());
}
}
}
}
Output:
key->apr
value->30
No comments:
Post a Comment