写了这么多Java程序,从来就没有过要获得Map中所有key,value值的需求,被人家一问就蒙了完全不知道啊。再说这也不是多难的东西,看来程序写的太少了。
import
java.util.HashMap;
import
java.util.Iterator;
import
java.util.LinkedHashMap;
import
java.util.Map;
import
java.util.Map.Entry;
import
java.util.Set;
import
org.junit.Test;
public
class
MapFetch {
@Test
public
void
funOne() {
Map map =
new
HashMap();
map.put(
"1"
,
"第一个数"
);
map.put(
"2"
,
"第二个数"
);
map.put(
"3"
,
"第三个数"
);
Set set = map.keySet();
Iterator it = set.iterator();
while
(it.hasNext()) {
String key = (String) it.next();
String value = (String) map.get(key);
System.out.println(key +
"="
+ value);
}
}
@Test
public
void
funTwo() {
Map map =
new
HashMap();
map.put(
"1"
,
"第一个数"
);
map.put(
"2"
,
"第二个数"
);
map.put(
"3"
,
"第三个数"
);
Set set = map.entrySet();
Iterator it = set.iterator();
while
(it.hasNext()) {
Entry entry = (Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key +
"="
+ value);
}
}
@Test
public
void
funThree() {
Map map =
new
LinkedHashMap();
map.put(
"1"
,
"第一个数"
);
map.put(
"2"
,
"第二个数"
);
map.put(
"3"
,
"第三个数"
);
for
(Object obj : map.keySet()) {
String key = (String) obj;
String value = (String) map.get(key);
System.out.println(key +
"="
+ value);
}
}
@Test
public
void
funFour() {
Map map =
new
LinkedHashMap();
map.put(
"1"
,
"第一个数"
);
map.put(
"2"
,
"第二个数"
);
map.put(
"3"
,
"第三个数"
);
for
(Object obj : map.entrySet()) {
Entry entry = (Entry) obj;
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key +
"="
+ value);
}
}
}