map的四种遍历方式

@Test
    public void test4() {
        Map<String,String> map = new HashMap<String,String>();
        map.put("1", "5");
        map.put("2", "6");
        map.put("3", "7");
        map.put("4", "8");
        System.out.println(map.size());
        //第一种  1 先获得key的集合  2 遍历key集合得到value (比较繁琐)
        Set<String> keySet = map.keySet();//获取键key的set的集合
        for (String in : keySet) {
            String string = map.get(in);
            System.out.println("key的值为=" + in + "value的值为=" + string);
        }
        System.out.println("------------------------------------------");
        //第二种 用entrySet 的iterator (entrySet一次性查找key 和value)
        Iterator<Entry<String, String>> iterator = map.entrySet().iterator();//将hash类型转化成集合型,然后用集合的迭代器取值
        while(iterator.hasNext()) {
            Entry<String, String> next = iterator.next();
            System.out.println("key的值为=" + next.getKey() + "value的值为=" + next.getValue());
        }
        System.out.println("---------------------------------------------------");
        //第三种  大数据存储时 key值复杂时推荐这种方法  
        for (Map.Entry<String, String> string : map.entrySet()) {
            System.out.println("key的值为=" + string.getKey() + "value的值为=" + string.getValue());
        }
        System.out.println("---------------------------------------------------");
        //第四种  只取value  当只取key值时推荐这种  
        for (String string : map.values()) {
            System.out.println("value值为=" + string);
        }
    }

TreeMap  也是如此 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值