entrySet()方法会返回key-value实体对的集合,此集合的类型即为Map.Entry,遍历时可以直接使用Map.Entry接口中的getKey(),getValue()方法;
keySet()则返回的是key的集合,需要在使用get()方法从map中取数据。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String[] args){
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("huawei",9000);
map.put("vivo",6000);
map.put("oppo",3000);
//使用entrySet遍历,推荐,尤其是容量大时
Set<Map.Entry<String,Integer>> set = map.entrySet();
for (Map.Entry<String,Integer> tmp : set){
System.out.println(tmp.getKey() + "价格是" + tmp.getValue().toString() + "元");
}
System.out.println("------------------------------------------");
//使用keySet遍历
Set<String> keys = map.keySet();
for (String tmp : keys){
//从map中取数据
System.out.println(tmp + "价格是" + map.get(tmp) .toString() + "元");
}
System.out.println("------------------------------------------");
//使用Iterator遍历
//注意这个迭代器对象的类型是Map.Entry
Iterator<Map.Entry<String,Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String,Integer> tmp = iterator.next();
System.out.println(tmp.getKey() + "价格是" + tmp.getValue().toString() + "元");
}
System.out.println("------------------------------------------");
//注意这个迭代器对象的类型是String
Iterator<String> keysIterator = map.keySet().iterator();
while (keysIterator.hasNext()){
String tmp = keysIterator.next();
System.out.println(tmp+ "价格是" + map.get(tmp).toString() + "元");
}
}
}
输出结果如下:
huawei价格是9000元
oppo价格是3000元
vivo价格是6000元
------------------------------------------
huawei价格是9000元
oppo价格是3000元
vivo价格是6000元
------------------------------------------
huawei价格是9000元
oppo价格是3000元
vivo价格是6000元
------------------------------------------
huawei价格是9000元
oppo价格是3000元
vivo价格是6000元
Process finished with exit code 0