Map集合

Map集合

特点

  1. 保存键和值
  2. 键不能重复
  3. 一个键对应一个值

有对应关系的就考虑使用Map来存储

代码实例

public static void main(String[] args) {

    HashMap<Integer,String> hs = new HashMap<>();

    hs.put(1,"xiaohong");//put---添加/修改
    hs.put(2,"xiaohuang");
    hs.put(3,"xiaohei");
    hs.put(4,"xiaobai");
    hs.put(5,"xiaolv");
    hs.put(6,"xiaohei");//当没有重复的键时,添加键值对并返回null;
    hs.put(1,"xiaolan");//当有重复的键时,会进行修改操作,并返回被修改的值

    System.out.println(hs);

    System.out.println(hs.get(1));//xiaolan 通过键来获取对应的值

    hs.remove(2);//删除键为2的xiaohuang键值对
    System.out.println(hs);//{1=xiaolan, 3=xiaohei, 4=xiaobai, 5=xiaolv, 6=xiaohei}

    System.out.println(hs.size());//5  获取map中的键值对个数
}

Map的遍历

Map遍历就是依次取出每个键和值(一次获取一对)

代码实例

通过键找值
public static void main(String[] args) {

    HashMap<Integer,String> hs = new HashMap<>();

    hs.put(1,"xiaohong");//put---添加/修改
    hs.put(2,"xiaohuang");
    hs.put(3,"xiaohei");
    hs.put(4,"xiaobai");
    hs.put(5,"xiaolv");
    hs.put(6,"xiaohei");//当没有重复的键时,添加键值对并返回null;

    Set<Integer> key = hs.keySet();

    for (Integer i : key) {

        System.out.println(hs.get(i));
    }


}
Entry键值对遍历

​ 是一个接口,表示键值对对象,里面会保存键和值,Entry相当于结婚证

遍历步骤

​ 1.得到所有的Entry
​ 2.遍历得到每个Entry
​ 3.通过Entry得到键和值

代码实例
 public static void main(String[] args) {

        HashMap<Integer, String> hs = new HashMap<>();
        hs.put(1, "xiaohong");//put---添加/修改
        hs.put(2, "xiaohuang");
        hs.put(3, "xiaohei");
        hs.put(4, "xiaobai");
        hs.put(5, "xiaolv");
        hs.put(6, "xiaohei");//当没有重复的键时,添加键值对并返回null;

        Set<Map.Entry<Integer, String>> se = hs.entrySet();

//        System.out.println(se);

        for (Map.Entry<Integer, String> i : se) {

            System.out.println(i.getKey() +"------"+i.getValue());
            //getKey()获取键
            //getValue()获取值
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值