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

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价格是6000Process finished with exit code 0
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值