Sample code to read Map collection entries.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ReadMap {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String,String>();
m.put("One","Number one");
m.put("Two","Number two");
m.put("Three","Number three");
long st = System.currentTimeMillis();
//#1
for (Map.Entry<String, String> entry : m.entrySet())
{
System.out.println(">>Key = " + entry.getKey()
+ ", Value = " + entry.getValue());
}
System.out.println(">>#1 - Run time ::: " +
(System.currentTimeMillis() - st) + "\n" );
//#2
st = System.currentTimeMillis();
for (String key : m.keySet())
{
String value = m.get(key);
System.out.println(">>Key = " + key
+ ", Value = " + value);
}
System.out.println(">>#2 - Run time ::: "
+ (System.currentTimeMillis() - st) + "\n" );
//#3
st = System.currentTimeMillis();
for (String key : m.keySet())
{
System.out.println(">>Key = " + key);
}
System.out.println(">>#3 - Run time ::: "
+ (System.currentTimeMillis() - st) + "\n" );
//#4
st = System.currentTimeMillis();
for (String value : m.values())
{
System.out.println(">>Value = " + value);
}
System.out.println(">>#4 - Run time ::: "
+ (System.currentTimeMillis() - st) + "\n" );
//#5
st = System.currentTimeMillis();
Iterator<Map.Entry<String, String>> iter =
m.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry<String, String> entry = iter.next();
System.out.println(">>Key = " + entry.getKey()
+ ", Value = " + entry.getValue());
}
System.out.println(">>#5 - Run time ::: "
+ (System.currentTimeMillis() - st) + "\n" );
//#6
st = System.currentTimeMillis();
Iterator iter1 = m.entrySet().iterator();
while (iter1.hasNext())
{
Map.Entry entry = (Map.Entry) iter1.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
System.out.println(">>#6 - Run time ::: "
+ (System.currentTimeMillis() - st) + "\n" );
}//End main method
}//End class
This is the output of the class when run.
>>Key = One, Value = Number one
>>Key = Two, Value = Number two
>>Key = Three, Value = Number three
>>#1 - Run time ::: 1
>>Key = One, Value = Number one
>>Key = Two, Value = Number two
>>Key = Three, Value = Number three
>>#2 - Run time ::: 1
>>Key = One
>>Key = Two
>>Key = Three
>>#3 - Run time ::: 0
>>Value = Number one
>>Value = Number two
>>Value = Number three
>>#4 - Run time ::: 1
>>Key = One, Value = Number one
>>Key = Two, Value = Number two
>>Key = Three, Value = Number three
>>#5 - Run time ::: 1
Key = One, Value = Number one
Key = Two, Value = Number two
Key = Three, Value = Number three
>>#6 - Run time ::: 0
No comments:
Post a Comment