遍历HashMap的四种方法

在Map集合中

values():方法是获取集合中的所有的值----没有键,没有对应关系,

KeySet():
将Map中所有的键存入到set集合中。因为set具备迭代器。所有可以迭代方式取出所有的键,再根据get方法。获取每一个键对应的值。 keySet():迭代后只能通过get()取key

entrySet():
Set<Map.Entry<K,V>> entrySet() //返回此映射中包含的映射关系的 Set 视图。 Map.Entry表示映射关系。entrySet():迭代后可以e.getKey(),e.getValue()取key和value。返回的是Entry接口 。

package xtgis.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class test {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("11", "1");
        map.put("22", "2");
        map.put("33", "3");
        map.put("44", "4");
        map.put("55", "5");
        map.put("66", "6");
        map.put("88", "8");
        map.put("99", "9");
        show_1(map);
        System.out.println("\n");
        show_2(map);
        System.out.println("\n");
        show_3(map);
        System.out.println("\n");
        show_4(map);
    }

    public static void show_1(Map<String, String> map) {
        for (String key : map.keySet()) {
            System.out.println("Key=" + key + " Value=" + map.get(key));
        }
    }

    public static void show_2(Map<String, String> map) {
        Iterator<Map.Entry<String, String>> maplist = map.entrySet().iterator();
        while (maplist.hasNext()) {
            Map.Entry<String, String> entry = maplist.next();
            System.out.println("Key=" + entry.getKey() + " Value=" + entry.getValue());
        }
    }

    public static void show_3(Map<String, String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key=" + entry.getKey() + " Value=" + entry.getValue());
        }
    }

    public static void show_4(Map<String, String> map) {
        for (String value : map.values()) {
            System.out.println("Value= " + value);
        }
    }
}


运行结果:

Key=11 Value=1
Key=22 Value=2
Key=33 Value=3
Key=44 Value=4
Key=55 Value=5
Key=66 Value=6
Key=88 Value=8
Key=99 Value=9

Key=11 Value=1
Key=22 Value=2
Key=33 Value=3
Key=44 Value=4
Key=55 Value=5
Key=66 Value=6
Key=88 Value=8
Key=99 Value=9

Key=11 Value=1
Key=22 Value=2
Key=33 Value=3
Key=44 Value=4
Key=55 Value=5
Key=66 Value=6
Key=88 Value=8
Key=99 Value=9

Value= 1
Value= 2
Value= 3
Value= 4
Value= 5
Value= 6
Value= 8
Value= 9

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值