1.测试类
package com.xiaolin;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class Bianli {
@Test
public void study() {
// TODO Auto-generated method stub
Map<String, String> map = new HashMap<String, String>();
map.put("a", "张三");
map.put("b", "李四");
map.put("c", "王五");
map.put("d", "赵六");
System.out.println("方法一:将Map集合中的映射关系取出,存放到set集合中.");
Set<String> key = map.keySet();
for (String a : key) {
System.out.println(a + ":" + map.get(a));
}
System.out.println("方法二:使用迭代器方法");
Iterator<String> it = key.iterator();
while (it.hasNext()) {
String key1 = it.next();
String value = map.get(key1);
System.out.println(key1 + ":" + value);
}
System.out.println("方法三:将Map集合中的映射键值对取出。存入到Set集合");
Set<Map.Entry<String, String>> entry = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entry.iterator();
while(iterator.hasNext()){
Map.Entry<String, String> map2 = iterator.next();
String key2 = map2.getKey();
String value = map2.getValue();
System.out.println(key2 + ":" + value);
}
System.out.println("方法四:通过Map.entrySet遍历key和value(最好的方法,尤其是容量打算)");
for(Map.Entry<String, String> entrySet : map.entrySet()){
System.out.println("key:" + entrySet.getKey() + " " + "value:" + entrySet.getValue() );
}
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class Bianli {
@Test
public void study() {
// TODO Auto-generated method stub
Map<String, String> map = new HashMap<String, String>();
map.put("a", "张三");
map.put("b", "李四");
map.put("c", "王五");
map.put("d", "赵六");
System.out.println("方法一:将Map集合中的映射关系取出,存放到set集合中.");
Set<String> key = map.keySet();
for (String a : key) {
System.out.println(a + ":" + map.get(a));
}
System.out.println("方法二:使用迭代器方法");
Iterator<String> it = key.iterator();
while (it.hasNext()) {
String key1 = it.next();
String value = map.get(key1);
System.out.println(key1 + ":" + value);
}
System.out.println("方法三:将Map集合中的映射键值对取出。存入到Set集合");
Set<Map.Entry<String, String>> entry = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entry.iterator();
while(iterator.hasNext()){
Map.Entry<String, String> map2 = iterator.next();
String key2 = map2.getKey();
String value = map2.getValue();
System.out.println(key2 + ":" + value);
}
System.out.println("方法四:通过Map.entrySet遍历key和value(最好的方法,尤其是容量打算)");
for(Map.Entry<String, String> entrySet : map.entrySet()){
System.out.println("key:" + entrySet.getKey() + " " + "value:" + entrySet.getValue() );
}
}
}
2.测试结果
方法一:将Map集合中的映射关系取出,存放到set集合中.
a:张三
b:李四
c:王五
d:赵六
方法二:使用迭代器方法
a:张三
b:李四
c:王五
d:赵六
方法三:将Map集合中的映射键值对取出。存入到Set集合
a:张三
b:李四
c:王五
d:赵六
方法四:通过Map.entrySet遍历key和value(最好的方法,尤其是容量打算)
key:a value:张三
key:b value:李四
key:c value:王五
key:d value:赵六