当前位置: 代码迷 >> 综合 >> Java中遍历Map的方法:entrySet(),和keySet()
  详细解决方案

Java中遍历Map的方法:entrySet(),和keySet()

热度:57   发布时间:2024-01-10 23:01:28.0

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.EntryIterator<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("------------------------------------------");//注意这个迭代器对象的类型是StringIterator<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价格是6000Process finished with exit code 0
  相关解决方案